March 21, 2012 .NET, C#, QuickTip No comments
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.
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:
You should see something like this:
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.
5) Go to IIS -> your FTP site –> Basic Settings –> Connect as… –> Specific User. And enter same user again.
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:
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:
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:
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,
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.
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.
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/
Та не забудьте подякувати автору, поширивши посилання.
January 22, 2012 Book Reviews 2 comments
In 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.
January 22, 2012 Book Reviews No comments
This 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:
Dear Reader, I would recommend this book for your leisure.
January 21, 2012 Book Reviews No comments
An astonishing book about life of amazing man, who changed the world.
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.
January 21, 2012 Success, YearPlanReport 7 comments
January 12, 2012 Revision of my activity, Success, YearPlanReport 1 comment
![]() |
Wedding-Preview-900px-2 |
![]() |
2011.07.23-29.Europe.Trip.Honey.Week |
December 15, 2011 Book Reviews No comments