Working with FTP for the first time? Quick setup & quick C# code.

March 21, 2012 .NET, C#, QuickTip No comments

Recently I had some FTP work to do. Nothing special, but in case you need quick guide on setting up FTP and writing access code in .NET you might find this interesting. Also you know where to find it in case you need it later.

I will define simple task and we will solve it!

Task:

Imagine we have external FTP server, where some vendor puts many files. Of course they provided us with credentials. We want to connect to server and then parse some files from the whole list of files. Also for testing purposes we are going to mock external service with our own local.

Setup FTP:

1) Enable FPT in Windows features.

image

2) Go to IIS –> Sites –> “Add FPT Site…”. You would need to specify some folder.

3) As for our task we want to mock some system. Following setup might be good:

  • Binding with all assigned host names and port 21
  • No SSL
  • Allow for Anonymous and Basic Authentication
  • Add Read permissions for All Users and Anonymous

You should see something like this:

image

image

You will be able to access FTP locally without any issues and need to provide credentials.

4) Go to User Accounts –> Advanced –> Advanced –> New User… Create user you would like use when connecting to FTP.

image

5) Go to IIS -> your FTP site –> Basic Settings –> Connect as… –> Specific User. And enter same user again.

image

We added this user because we need to imitate situation in which our code and FTP have different credentials.

Access code:

To get list of files on server (using WebRequest):

public List<string> FetchFilesList()
{
    var request = WebRequest.Create(FtpServerUri);
    request.Method = WebRequestMethods.Ftp.ListDirectory;

    request.Credentials = new NetworkCredential(UserName, UserPassword);

    using (var response = (FtpWebResponse)request.GetResponse())
    {
        var responseStream = response.GetResponseStream();

        using (var reader = new StreamReader(responseStream))
        {
            var fileNamesString = reader.ReadToEnd();
            var fileNames = fileNamesString.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            return fileNames.ToList();
        }
    }
}

To fetch some file contents as XDocument (using WebClient):

public XDocument FetchFile(string fileName)
{
    var client = new WebClient();
    client.Credentials = new NetworkCredential(UserName, UserPassword);

    var fileUri = new Uri(FtpServerUri, fileName);
    var downloadedXml = client.DownloadString(fileUri);
    return XDocument.Parse(downloadedXml);
}

I don’t think those two chucks of code need lot of explanations. As you can see with WebClient there is less code, but this way you cannot specify request ftp method.

Hope this overview is quick and not too much noisy.

NOTE: I’m not professional administrator, so my FTP setup may be somewhatwrong, but it satisfied needs of task described in the beginning of blog post.

In any case here are some links:


No comments


Custom configuration: collection without “add” plus CDATA inside

March 20, 2012 .NET, C#, QuickTip 2 comments

This blog post might look like any other standard blog posts, answering question, which can be googled and found on stackoverflow. But it isn’t. You see… it composes couple of interesting things you might need for you custom configuration. Also it is not congested with explanations. I’m adding this as quick reference for myself, so I don’t spend my time googling a lot to find answers. Also if you just starting with custom configuration and don’t want to read MSDN pages, please refer to my earlier blog post on basics here.

Let’s get back to topic:

We want section in our app/web.config with collection which will be able to contain elements without ugly “add” tag and also have CDATA inside. See configuration:

    <Feeds defaultPollingInterval="00:10:00">
      <Feed>
        <![CDATA[http://www.andriybuday.com/getXmlFeed.aspx?someParam=A&somethingElse=B]]>
      </Feed>
      <Feed pollingInterval="00:05:00">
        <![CDATA[http://www.andriybuday.com/getXmlFeed.aspx?someParam=C&somethingElse=D]]>
      </Feed>
    </Feeds>

So as you can see in collection of elements there is custom name “Feed”, which is awesome. Also notice that URL contains weird characters (not for us, but for XML), so we surround URL into CDATA. Those feeds are fake of course.

To make all this happen we need few things:

  1. Override CollectionType property for our collection, and set type to BasicMap
  2. Override ElementName property for our collection, and return preferred name
  3. Override DeserializeElement method for element inside collection. Here you need to manually fetch your attributes, like I do for poollingInterval and read contents of CDATA. Please refer to source code below to see how this is done as it is bit tricky. For example because of the nature of the XmlReader you need to read attributes first and then proceed to contents.

Source code below (interesting pieces are in bold):

[ConfigurationCollection(typeof(FeedConfigElement))]
public class FeedsConfigElementCollection : ConfigurationElementCollection
{
    [ConfigurationProperty("defaultPollingInterval", DefaultValue = "00:10:00")]
    public string DefaultPollingInterval
    {
        get
        {
            return (string)base["defaultPollingInterval"];
        }
    }
    protected override ConfigurationElement CreateNewElement()
    {
        return new FeedConfigElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((FeedConfigElement)(element)).Url;
    }

    // In order to avoid standard keyword "add"
    // we override ElementName and set CollectionType to BasicMap
    protected override string ElementName
    {
        get { return "Feed"; }
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get { return ConfigurationElementCollectionType.BasicMap; }
    }
    public FeedConfigElement this[int index]
    {
        get
        {
            return (FeedConfigElement)BaseGet(index);
        }
    }
}

public class FeedConfigElement : ConfigurationElement
{
    public string Url { get; private set; }

    public string PollingInterval { get; private set; }

    // To get value from the CDATA we need to overrride this method
    protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
    {
        PollingInterval = reader.GetAttribute("pollingInterval") ?? "00:00:00";

        // Also for some unknown reason for CDATA ReadElementContentAsString returns 
        // a lot of spaces before and after the actual string, so we Trim it
        Url = reader.ReadElementContentAsString().Trim();
    }
}

Hope this gives quick answers to some of you. It took me good portion of time to find all this things, because for some odd reason it wasn’t so much easy to find.

Some links:


2 comments


WP7 update error 80070026

March 19, 2012 QuickTip, WP7 No comments

I can assume this is of no use for most of you, my constant readers.

But in case you googled for this or just happened to have Windows Phone 7 and cannot update it because of the error 80070026, which you see on the image below,

WindowsPhone7_HTCMozart_UpdateError_80070026

please know: the only solution that helps is complete reset.

Don’t waste your time on searching for solutions – I did it for you. Also reset is not that painful as you might imagine. Just ensure you have all your media and application data backed-up to some clouds or at least local drive. With good internet connection, which no doubt you have at home, reinstallation of apps is super quick, plus you will get rid of junk apps.

To reset either go to “Settings->About->Reset you phone” or use more geeky way with using phone buttons: turn off phone, then press both volume up and down buttons and hold and then press the power button (briefly) to switch the phone on. When you see reset screen release volume buttons and follow instructions.

You might be interested to know if there are some specifics to my situation, so here they are:

Phone: HTC Mozart T8698
Update: 7.10.7740.16 => 7.10.8107.79
When: On performing actual update
OS: Windows 7
Zune: latest version possible

Some links in case you have other update troubles:

 

If you found another solution to this problem please let me know.


No comments


My book on design patterns is released

February 15, 2012 Book Reviews, Design Patterns, Success 23 comments

Dear Reader,

I’m glad to let you know, that I released my short free e-book on design patterns.

BookCover_480

It is available on web site https://designpatterns.andriybuday.com/

As you many know early 2010 I started writing series of blog post dedicated to GoF design patterns. I tried to keep my examples of patterns very simple and in the way, that person reading example can build associations with real or close to real world situations. I also translated all of the examples into Ukrainian and then decided to assemble small e-book. And now it is available for you.

Here is some introduction in Ukrainian (I’m not translating it to English, since if you cannot read in Ukrainian there is no point).

Опис
Книга «Дизайн патерни — просто, як двері» є безплатною україномовною книгою, що містить унікальні приклади до шаблонів проектування. Завдяки своїй нестандартній подачі матеріалу вона дозволить вам легко опанувати основи розуміння дизайн патернів чи систематично і дуже швидко повторити їх перед інтерв’ю. Спосіб написання книги дозволить провести час, відведений на її прочитання, без нудьги, а подекуди навіть захоплююче.
Освіжіть у своїй пам’яті призабуті дизайн патерни!

Завантажити книгу

У декількох словах
Книгу я написав із добрими намірами. Їх у мене було декілька. Я хотів упевнитися, що сам розумію усі класичні дизайн патерни. Ресурсів для цього є досить багато, але я вирішив реалізувати ці патерни самостійно та придумати власні приклади. Таким чином, починаючи із 16 січня 2010 я писав блог пости, які так чи інакше викликали зацікавлення в читачів. Щоб цей внесок в програмування був більш чітким, в мене виникло бажання випустити невеличку книжку, яка стала б колекцією цих блог постів.

Завітайте на сайт книги: http://designpatterns.andriybuday.com/
Та не забудьте подякувати автору, поширивши посилання.


23 comments


Book Review: “Silverlight 4 in Action”

January 22, 2012 Book Reviews 2 comments

imageIn the light of Microsoft’s decision on the future of Silverlight it doesn’t sound heroic that I read "Silverlight 4 in Action" also taking into account that Pete Brown already released new edition of book for latest and last 5-th version of SL.

But I had read book couple of months ago before SL5 was released. I read it with my friends at work and it was joy.

“Silverlight 4 in Action” on Amazon

It is somewhat standard step by step tutorial on particular technology. But it provides really comprehensive look at Silverlight.

If you use this technology, book is great asset to understanding Silverlight.


2 comments


Book Review: “Drive: The Surprising Truth About What Motivates Us”

January 22, 2012 Book Reviews No comments

imageThis book is very interesting. Even it might not bring lot of eye-opening information for software developer as we are on the edge of innovations in many respects (my personal thought) it supplies us with information for deeper understanding of why we do what we do.

“Drive: The Surprising Truth About What Motivates Us” on Amazon

Indeed this books uncovers inner mechanisms of motivation gears inside of us. Some gears refuse to spin or just slip when we try to solve different problems. Sometimes we need to unpack brand new gears and install those to gain additional boost.

Book reveals evolution of motivation principles from Motivation 1.0 which is based on instincts to Motivation 2.0 which is based on stick and carrot and finally to Motivation 3.0 based on inner drive and not external factors.

Watch this video for inspiration:

RSA Animate – Drive: The surprising truth about what motivates us

Dear Reader, I would recommend this book for your leisure.



No comments


Book Review: “Steve Jobs”

January 21, 2012 Book Reviews No comments

image

An astonishing book about life of amazing man, who changed the world.

“Steve Jobs” at Amazon

Book reveals many interesting facts about his youth, his addiction to the excellence of things, his contradictions and way he dealt with people.

For me reading this book was extremely enjoyable. I never thought that biography can be so much gripping and thought-provoking.

The more I think about the kick-off reason for him being so much great person the more I’m about to conclude that he attained success by constantly feeling that something is wrong with himself, and feeling the lack of something big in time when he was kid and youth. We know he was adopted son and he sought for wisdom in buddhism, and he took drugs and had other strange behavior. His strong self-confidence in his superior status allowed him to do stuff many would be scared to step into. His Reality Distortion Field allowed people do things they would never do.

From this book I got insight into what it means to be different, to live different, to think different and to build different world by your own acts.

Book is inspiring, provoking to think about world perception and business in deeper and more philosophical way.

Dear Reader, I would highly recommend you to read this book.



No comments


Where Do You Want to Be In a Year?

January 21, 2012 Success, YearPlanReport 7 comments

Dear Reader,
This is continuation of my year plan/report thread. I had similar plan for 2010 and for 2011. Completion of 2010 list was almost 100% successful, and completion of 2011 was much difficult and not so successful, but 2011 brought many life turning events and decisions.
I’m frustrated to admit that my head doesn’t carry this phrase all the time:
Remember, life is limited in time, so if I don’t move in the right direction I will waste it entirely. 
Here below is my resolution list for 2012
  1. Buy a car in Europe (some used German car)
  2. Travel though major cities in Austria (Vienna, Salzburg, Linz, Graz, Innsbruck, Bregenz, Eisenstadt, Klagenfurt)
  3. Sport activities (have two-three summer hikes into the Alps & ski in the Alps)
  4. Learn German for at A2 level (which is elementary)
  5. Improve English and rich C1 level (which is advanced)
  6. Show kick-ass performance at work
  7. Get promotion (or get clear idea on career opportunities, if not possible)
  8. In Vienna find local .net community (user group, whatsoever) and join
  9. Visit TechEd Europe or NDC2012 (if possible because of budged considerations)
  10. Have new friends in Austria, who share same opinions
  11. Write couple of WP7 applications and post them to marketplace
  12. Write couple of Win8Metro applications for fun
  13. Release “Design Patterns” Book – I have 1 month to do so
  14. Read 15 books (see my LinkedIn reading list)
  15. Learn programming language(s). I will start with “7 languages in 7 weeks” and then pick up one for deeper insight (not compulsory from book)
  16. Discipline myself to get up at some certain time
  17. Have more public visibility and community impact – my way to MVP
My next annual report should contain evidence in facts to prove completion of above resolution. This resolution is bit smaller than 2011’s one, but as reality shows it should be more achievable because of this.
Please share your year resolution list! I will read with pleasure.


7 comments


What I have done in 2011

January 12, 2012 Revision of my activity, Success, YearPlanReport 1 comment

Looking back at my “Where do you want to be in a year?” blog post for the Jan 9, 2011, I regret that I did not do many things I planned, but I’m also proud about many things I did, because many of them are not small ones, but rather life changing, like marriage and moving to other country.

Overview of 2011

At the beginning of the year I continued passing my MS exams, which seemed somewhat important and very valuable for me at that moment, also I enjoyed end of winter spending many days at skiing hills in mountains. Near that time me with girlfriend decided to let our parents know our decision about future marriage in summer. They started to be in rush, but not me – at the beginning of sprint I had been thinking more about choosing my first car, which I successfully bought for 7000$. It is used Chevrolet Aveo 2005 of fully equipped, except it has manual transmission. At the day I bought car I did not have place to live in Lviv – me with best friend where looking for new apartment to rent, because of crazy and alcoholic owner of apartment, we rented before.
My blog did not go well previous year. There are couple of months without blog posts. One of them is July. It was very hot month – I got married on 16th of July and while still having vacation we went to Europe trip to see Hungary, Austria and Switzerland the most.
Besides of Europe trip we with my wife visited really many places in Western Ukraine. Now we had car, so travelling was more quick and spontaneous. 
By coincidence I was asked if I’m not interested to pass interview and relocate to other country just before my marriage. It went well and I was asked for other interview which by great coincidence was on-site in Austria when I was there with my wife. She was admiring Belvedere in Vienna, while I had my 1,5 hour interview. So in August I got an offer and accepted it. But as it is relocation to other country it involves lot of paper work to get work permit there, and took almost half a year to get approval.
This year also brought more responsibility for me at work, I had much of Technical Leader responsibilities & activities. I think that I worked in the most amazing and truly collaborative team from all of those I had chance to work in. We worked on WP7 project and challenging Silverlight project. I left those guys just before the winter, hoping to have few weeks of rest before final approval and relocation to Austria.
Before the New Year of 2011 I didn’t get approval so my “vacation” took longer, but I spent it reading a lot, sleeping even more, doing some pet coding and getting extremely lazy. To summarize: you won’t enjoy being unemployed for longer than month, not because of the money, but because of lacking social relations and absence of external challenges.

Was 2011 going according to my year plan?

See plan here.
– Release awesome free Design Patterns book in Ukrainian
I failed to do this in 2011, but I composed book, sent it to people willing to review its raw unedited version. As for now I have 5 our 25 responses on book. I’m going to create small web site for book and publish it there.
– Enterprise certification (finishing with 565 exam, very likely till the end of Winter)
I passed exam and got MCPD: Enterprise Application Developer at the beginning of the year.
– Learn to ski & swim well (I can both, but I want to be good at that)
I’m now above intermediate in skiing, but this is subjective view. Fact is that I can handle most difficult hills in Ukraine, like trostian on picture below and “black” trails in bukovel, can do basic ski-jumps and ski backwards.
image
As of swimming I did complete fail as I’ve been in water only 2 times during the year.
– Show kick-ass performance at work
I did not get official promotion, but I played role of Technical Leader, coded a lot and tried to show best of myself. I think I did great and could have done even better. Leaving this job was not an easy thing to do. I think SS is great Ukrainian company.
– Learn WP7 and Silverlight
Whole year I did coding for WP7 and out of browser application in Silverlight. Also with my friends won at Hackathon event, where we created small game for the WP7.
image
I also introduced weekly discussions around reading “Silverlight in Action” in my team.
– Start working on some “real” book (just collecting ideas on book)
As of now I don’t have any clear idea on “real” book. But the more I think on this matter the more I’m close to something on the edge of technology and people collaboration.
– Read 24 books (this year I will definitely hit this score)
Let’s count: 5 in reviews on blog, 4 more read, but no posts on blog yet. And also 5 in progress, 4 of which are almost read. (I tried hard to read as much as I can before New Year and that lead to 5 in progress).
In total it looks like not more that 13 books, which is even less than previous year report (15). Seems one book a month is my pace.
“Take quick look behind to analyze, don’t stop, think positively, go forward!” – I said to myself on this subject.
– Marriage (yeah, this really is in the list “OMG” I’m saying to myself…)
It is one of the things I’m proud about. Despite this world’s shifted mind I think that two can get married in their twenties and be happy for many years. I was really surprised by marriage statistics in Western countries. For example this statistics show that less people are getting married and along more are getting divorced. And this shows that my country is also at the top of divorce list. Too much about that crap.
Here we are:
image
And here are more of those photos at Picasa:
Wedding-Preview-900px-2
I’m extremely glad that I have so cute and smart wife. Just after marriage we travelled even more than before it. We have been enjoying each moment of being together.
Before I left work, we had been living in separate apartment not far from my friend and team-mate. Each day she prepared awesome breakfast and lunch to take to work. Then I picked up Taras and drove to work. It was routine, but it was great.
– Travel abroad (I’m planning for Europe tourist tour)
I had awesome week travelling though Europe after my wedding. See photos:
2011.07.23-29.Europe.Trip.Honey.Week
– Learn one more programming language (probably everyone heard about learning one language per year, why not?)
I read bits about Haskell and tried F#, but I’m not satisfied with my progress. So will have another try in 2012.
– Frequent dev meetings (this is hard, because preparing takes lot of time for me)
I did probably very few so called “developer’s meetings”, one of which was even paid. Despite this I introduced technical status meeting for my team in addition to scrum standup.
Karpaty alpinism (again health stuff, want to do this with my girlfriend)
We took Hoverla – the highest mountain in Ukraine:
image
Read complete story and see photos at my wife’s blog here.
We also been on hard Pikyj, read here and more enjoying Lopata (read here).
– Became known presenter (couple of outside the company presentations)
– English (watch films, find guys to talk in English)
For anything of video I watched myself I preferred English. Which of course didn’t work for cinema where I go with wife and friends. Also I had to watch amazing “The Big Bang Theory” translated, but some series watched with pleasure in English.
And what is funny now I’m learning German :).
– Start coffee-and-code in Lviv
Fail. I thought about this many times and always lacked confidence in my social skills to do this. Probably it can be as easy as mentioning on blog and in twitter something like “Hey, guys! Tomorrow I will be in the XYZ coffee shop doing some coding. Come along and join.”
– Write couple of personal-small programming projects / contribute to open-source
Not much here – dozen of try-it-out projects, small open-source orm system CustomORM, wp7 project we wrote at Hackathon and maybe 3 wp7 i-started-it-and-left projects, ah and few competition type projects at TopCoder.
– Visit one of the solid conferences
I visited couple of conferences like Uneta Plus and Mobile Professional Days in Kharkiv, and of course many events here in Lviv like LvivIT and regular Lviv User Group events.
– Get money machine / some ideas / investments / whatever
I haven’t invented anything better than deposit accounts, which now don’t work that good as if they worked in 2009 while crisis. Month interest income is enough for one full tank of my car, which usually runs out in 1-1,5 weeks.
– Start some business even small and crappy – but have it to learn
Fail. And even more – complete fail. I didn’t even think about this much. But from other point of view, there must be something exciting me to start with and I haven’t found anything like this. At least I’m happy that I will be eligible to have wp7 developer account in Austria.
Became better-and-better in planning and achieving, continue growing, etc, etc…
Subjective. Isn’t it? I think I did great with this one, but you decide. I move into embrace of 2012 year which will definitely bring me lot of nice surprises, emotions and great time.


1 comment


Book Review: “Code complete”

December 15, 2011 Book Reviews No comments

imageFinally this happened and I’ve read this long book. I started reading it probably 2 years ago :). I was not reading it all 2 years of course, I did it in 3 phases. For some reason (you can figure it out later in this post) I dropped it few times.
As “Code Complete” goes very long, I’m not sure I will be capable to write in any way corresponding review. But rather few words, so here they are:
“Code Complete” was intended to be comprehensive software development reference handbook with accent on construction. And indeed it was such kind of book maybe 10 or more years ago. I think that this book is bit outdated. Even with publishing 2cond edition contemporary trends are not included, rather they are are covered at surface. It can be even seen that they appeared later in the book. But we can look at this from positive perspective – which is learning how was programming when you dad was in charge :). In some places it was boring to read too-long and too much detailed explanations to obvious things. For example such trivial construction thing as loop was discussed in 20 pages long chapter. How many books do you know that observe loop from all possible viewpoints? Title of the book talks for itself.
Nevertheless “Code Complete” is full of examples and dozen of very interesting facts about software. In any way it was enjoyable to read brilliant metaphors, astonishing facts, discover new in known old. If you sharpening your skills and on your way of software craftsman “Code complete” has lot of advices for you, with references to hundreds of other books. In fact author worked hard to gather all information and create this masterpiece, and I’m really sorry that reality of software industry slightly kicks this book out of the shelf because of new technologies and new approaches to building software.
Do I recommend this book?
Yes, but don’t read it – review it and then read only the tasty bits.


No comments