I was in a need to get a type, instantiate it and then fill its properties (I'm currently doing an engine that will give me an instant CRUD UI).
So what I basically needed was to be able to fill a new object instance out of a Hashtable (the key is the name of the property and the value is its string representation).
I wanted to be able to convert that string value into the type it needs to be.
Here is some code to help you get it:
foreach(string strPropertyName in htValues.Keys)
{
PropertyInfo pi = entity.GetType()
.GetProperties()
.ToList()
.FirstOrDefault(property => property.Name == strPropertyName);
}
(this is kind of pretotype so don't blame me if you don't like the code :).
In the above code I am iterating in the keys of the hashtable, so if I have an user object it will strPropertyName will hold "FirstName", then "LastName".
So far so good, I am able to fill the object and send it to the EntityFramework for DB Persistance.
The problem was when the strPropertyName was holding "BirthDate" as it is a DateTime and the EntityFramework or the Reflection (not quite sure which one) was crying it can't Convert the string to the respective type for me.
Here is how I solved the problem:
// Create a new Instance of the given type.
object entity = Activator.CreateInstance(this.EntityType);
// Iterate through all the properties.
foreach(string strPropertyName in htValues.Keys)
{
// Get the property with that name:
PropertyInfo pi = entity.GetType()
.GetProperties()
.ToList()
.FirstOrDefault(property => property.Name == strPropertyName);
// Get the default type converter for the given property type:
TypeConverter converter = TypeDescriptor.GetConverter(pi.PropertyType);
// Set the value by converting non-values to the given type
// and setting null where it is a null value.
pi.SetValue(entity, htValues[pi.Name] == null ? null : converter.ConvertFromString(htValues[pi.Name].ToString()), new object[] { });
}
Basically the thing you (and I!) need to remember is that the TypeDescriptor class has a GetConverter() method that takes a type and returns a TypeConvertor for that type.
Now in order to be able to convert from string to that type you just need to call .ConvertFromString(string value) of the TypeConverter returned by the TypeDescriptor.
Hope this helps someone out there. To me it seems it can give you a great deal of abstraction and I (for some reason) believe this is heavilly used in nowadays OR/M's.
All the stuff that bothers software developer in his everyday tasks.
Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts
Jun 10, 2011
Jun 9, 2011
Get the underlying type out of a Nullable
It appeared to be really simple actually, this post title suggest the solution:
Type nonNullableType = null;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
nonNullableType = new NullableConverter(property.PropertyType).UnderlyingType;
else
nonNullableType = property.PropertyType;
What we actually do is to check if the type is nullable or not, if so - we are getting its Underlying type, and if not - we are getting the type itself.
Type nonNullableType = null;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
nonNullableType = new NullableConverter(property.PropertyType).UnderlyingType;
else
nonNullableType = property.PropertyType;
What we actually do is to check if the type is nullable or not, if so - we are getting its Underlying type, and if not - we are getting the type itself.
Етикети:
.NET,
.NET C# technologies,
C#,
Development
Jun 18, 2010
How does your manager make a coffee?

I had an architectural problem yesterday.
I was working on a methods and managers I won't disclose but will analogy instead.
Imagine you have a coffee manager. Let's name it CoffeeManager.
In my case not only I had coffee manager but also I had a SugarManager, a CupManager etc.
In order to take a coffee without sugar in a plastic cup I should do something like:
Sugar sugarObject = SugarManager.GetSugar(Sugar.None);
Cup plasticCup = CupManager.GetCup(Cups.PlasticCup);
Coffee shortCoffee = CoffeeManager.GetCoffee(sugarObject, plasticCup);
And this happens at the very frontend of the project (in ascx for example).
And not only it happens that way but the managers are spread in few different projects.
So in the frontend I need to call few different managers, get some results from them and pass those results to the manager that should be doing my job.
I also need to handle all the problems that may rise in the managers so I get a lot of code in the frontend just to get something that in my opinion for that particular case should be returned calling a single method and auto handled in the manager.
I think the front end shouldn't care about business operations that much, also as I said the managers were in different assemblies so I ended up adding few references to the frontend project.
I refactored the code so the CoffeeManager can do this job internally (drawback is that the matrix of all combinations of sugar and cup should be added as a methods in the CofeeManager, but I can live with that).
Dec 3, 2009
The specified service has been marked for deletion error message when removing a service
If you receive this message while trying to delete a windows service - check if the Services.msc application is open.
You will need to restart in order to delete the service, but you will know to first close the Services.msc application the next time PRIOR uninstalling the service (using installutil /u service_exe_name).
Hope this helps someone outthere...
Edit : I found another scenario when this can happen and it seems to be more .NET specific and common to software developers - if your service creates some worker threads, Windows will attempt to kill the main thread, the main thread will attempt to kill the main thread but the worker threads if not marked as BackgroundThreads via the IsBackgroundThread property will remain. The GC will wait for them to reach a safe point so they can be terminated and the service will most probably be only marked for deletion, requiring you to restart windows.
Please note - if you are using the ThreadPool class you will probably not hit this problem as the ThreadPool internal threads are automatically marked as background threads.
Edit 2: Another case when you will receive The specified service has been marked for deletion error message is when you try to uninstall service which wasn't stopped first or it was marked as unstopable.
This is done if you have this.CanStop = false in your service code.
Windows knows this service shouldn't be stopped and it will only mark it for deletion but will not delete it right away.
Be careful with CanStop property.
You will need to restart in order to delete the service, but you will know to first close the Services.msc application the next time PRIOR uninstalling the service (using installutil /u service_exe_name).
Hope this helps someone outthere...
Edit : I found another scenario when this can happen and it seems to be more .NET specific and common to software developers - if your service creates some worker threads, Windows will attempt to kill the main thread, the main thread will attempt to kill the main thread but the worker threads if not marked as BackgroundThreads via the IsBackgroundThread property will remain. The GC will wait for them to reach a safe point so they can be terminated and the service will most probably be only marked for deletion, requiring you to restart windows.
Please note - if you are using the ThreadPool class you will probably not hit this problem as the ThreadPool internal threads are automatically marked as background threads.
Edit 2: Another case when you will receive The specified service has been marked for deletion error message is when you try to uninstall service which wasn't stopped first or it was marked as unstopable.
This is done if you have this.CanStop = false in your service code.
Windows knows this service shouldn't be stopped and it will only mark it for deletion but will not delete it right away.
Be careful with CanStop property.
Nov 24, 2009
Limiting your Internet connection speed with Fiddler.
In some cases you may need to limit your connection for testing purposes.
This is / should be extremely easy using Fiddler.
Here is a simple walkthrough on how to do this:
1. Go to Fiddler site and download Fiddler latest version (http://www.fiddler2.com/fiddler2/)
2. Install it and start it.
3. Click on Rules -> Customize Rules:

4. An instance of notepad should open. Find the line that says something like "oSession["request-trickle-delay"]":

This setting tells Fiddler how much milliseconds should halt the request. (not quite sure how a request halt will help you though)
5. Find the line that says "oSession["response-trickle-delay"]" and change it:

Save the file.
You should have a connection limitation.
Now, when you want your connections slowed down, you will need to check the following option:
6. Rules -> Performance -> Simulate Modem Speeds (should be checked):

Please do not forget to switch off fiddler when you don't need it as you may find yourself wondering why is your connection significantly slower than usual ;).
Hope it helps someone out there.
This is / should be extremely easy using Fiddler.
Here is a simple walkthrough on how to do this:
1. Go to Fiddler site and download Fiddler latest version (http://www.fiddler2.com/fiddler2/)
2. Install it and start it.
3. Click on Rules -> Customize Rules:

4. An instance of notepad should open. Find the line that says something like "oSession["request-trickle-delay"]":

This setting tells Fiddler how much milliseconds should halt the request. (not quite sure how a request halt will help you though)
5. Find the line that says "oSession["response-trickle-delay"]" and change it:

Save the file.
You should have a connection limitation.
Now, when you want your connections slowed down, you will need to check the following option:
6. Rules -> Performance -> Simulate Modem Speeds (should be checked):

Please do not forget to switch off fiddler when you don't need it as you may find yourself wondering why is your connection significantly slower than usual ;).
Hope it helps someone out there.
Aug 2, 2009
W3C Zoom CSS property. I really want this feature included!!!
Lot's of people are discussing this.
And the designers are often saying something like:
"I cannot imagine a scenario where you will need to use the Zoom CSS property."
To the readers that haven't yet hit this problem - the CSS Zoom property seems to be proprietary and to be working for IE (I think version 6 and above).
To all those designers - there ARE scenarios where you will want to let the user zoom everything proportionally without using the browser buttons / sliders / shortcuts, but with CSS / JS only.
I will give you few examples:
1. I needed to create an overview control of page. It should represent the page in a smaller percentage and, upon scroll, the page should scroll proportinally. I can have a div with the same DOM tree (or even an IFrame loading the same page or something). In this case I URGENTLY need the CSS Zoom property.
2. Telerik radReporting - the ReportViewer has a dropdown to let the user choose a zoom level to preview the page (web based and not after clicking print preview or something). Actually the Print Preview browser command isn't an option as the report viewer may be on the page with other controls and the user SHOULD BE ABLE to zoom in and out only the portion of the page where the report is (it is an IFrame with the data rendered as HTML, I believe). In telerik case - there seems to be some browser detection and when the browser isn't capable of zooming in / out - the dropdown with the zooming levels is simply hidden (they have no other choice unfortunatelly and I support them for this decision).
Now, as you may expect - in my scenario I cannot simply hide the overview control as the page heavilly depends on it.
Should I now have my revenge now? I've seen all those messages accross the web telling you that there are better browsers to use than IE.
Should I now display a message like:
"Sorry, your browser isn't capable of zooming in and out, only IE supports this, so please switch to IE."
I really hate those browser wars and if you really want to know my opinion - yes, IE may be harder to design. It may be messing up the containers, it may not be passing the ACID N test.
But it is the only browser that is suitable for my scenario (at least from my search in IE all the posts were following the same line - "zoom is IE proprietary, it won't work under other browsers").
Why are all other browsers sleeping then?
P.S. I have found something like -moz-zoom or something but wasn't able to make it work under FireFox (if it works under Firefox it should also probably work under Google Chrome as they are using the same engine I think).
P.P.S. - haven't tested but I think the zoom CSS property should also be available under Opera as they (as far as I know) use the IE core.
P.P.P.S - if anyone know how can we ask W3C to reconsider this for at least the next revision of CSS I would be glad to give my vote. I also advice telerik to do the same. Not only the reporting will work in all browsers but they may be able to do some other great controls using this property.
Really annoying ...
And the designers are often saying something like:
"I cannot imagine a scenario where you will need to use the Zoom CSS property."
To the readers that haven't yet hit this problem - the CSS Zoom property seems to be proprietary and to be working for IE (I think version 6 and above).
To all those designers - there ARE scenarios where you will want to let the user zoom everything proportionally without using the browser buttons / sliders / shortcuts, but with CSS / JS only.
I will give you few examples:
1. I needed to create an overview control of page. It should represent the page in a smaller percentage and, upon scroll, the page should scroll proportinally. I can have a div with the same DOM tree (or even an IFrame loading the same page or something). In this case I URGENTLY need the CSS Zoom property.
2. Telerik radReporting - the ReportViewer has a dropdown to let the user choose a zoom level to preview the page (web based and not after clicking print preview or something). Actually the Print Preview browser command isn't an option as the report viewer may be on the page with other controls and the user SHOULD BE ABLE to zoom in and out only the portion of the page where the report is (it is an IFrame with the data rendered as HTML, I believe). In telerik case - there seems to be some browser detection and when the browser isn't capable of zooming in / out - the dropdown with the zooming levels is simply hidden (they have no other choice unfortunatelly and I support them for this decision).
Now, as you may expect - in my scenario I cannot simply hide the overview control as the page heavilly depends on it.
Should I now have my revenge now? I've seen all those messages accross the web telling you that there are better browsers to use than IE.
Should I now display a message like:
"Sorry, your browser isn't capable of zooming in and out, only IE supports this, so please switch to IE."
I really hate those browser wars and if you really want to know my opinion - yes, IE may be harder to design. It may be messing up the containers, it may not be passing the ACID N test.
But it is the only browser that is suitable for my scenario (at least from my search in IE all the posts were following the same line - "zoom is IE proprietary, it won't work under other browsers").
Why are all other browsers sleeping then?
P.S. I have found something like -moz-zoom or something but wasn't able to make it work under FireFox (if it works under Firefox it should also probably work under Google Chrome as they are using the same engine I think).
P.P.S. - haven't tested but I think the zoom CSS property should also be available under Opera as they (as far as I know) use the IE core.
P.P.P.S - if anyone know how can we ask W3C to reconsider this for at least the next revision of CSS I would be glad to give my vote. I also advice telerik to do the same. Not only the reporting will work in all browsers but they may be able to do some other great controls using this property.
Really annoying ...
Nov 14, 2008
Two new automated blogs
| I've been very busy this month. All the exams (for microsoft certification, in the faculty and so on), my extended work day (from 9 to 20 as I was absent |
However, I've found some time to start two new blogs which I consider more as experiment than real blogs:
Sql Exceptions
and :
.NET Exceptions
Both blogs currently contain about 40 posts with Sql and .NET Exceptions which you may find helpful after time. I am saying after time as I plan to automate those blogs so the information there is posted by software and not by myself.
Also users are welcome to post comments. Soon I will publish special format of posts which you can use in order to give your opinion on specific exception and this exception will be automatically published in the post.
Unfortunatelly there is a limitation - Blogger allow me to only publish about 40 posts daily so I wasn't able to create posts about all the exceptions in SQL and .NET Framework.
I will batch post each day (may miss some of the days like weekends for example ;) so in few weeks both blogs will be up to date.
Nov 5, 2008
On the asp.net official site for the very first time!
| Well, a lot of people don't consider showing someone on the official asp.net site a big deal. There is a box "Community recognition program" where the most active members as well as yesterday's most active members are shown. I had 102 points for the previous day so I appeared. It really isn't big deal, but I consider it a big start, because it gave me motivation to continue to contribute. It is not about the recognition. In asp.net site you can find a lot of friends also. It is great to help someone and then see something like : "Dude, you're |
Here is a screenshot I will keep close to my heart :D
Oct 21, 2008
C# AddIn - Start Debugging and get the running Internet Explorer instance.
| I needed to do this (actually I wanted). I was curious if you can obtain an instance of a Internet Explorer which was started in debugging session. Here is a snipet to do this: _applicationObject.Debugger.Go(false); SHDocVw.ShellWindowsClass windows = new ShellWindowsClass(); foreach (SHDocVw.InternetExplorer explorer in windows) { if (explorer.LocationURL == string.Empty) { // this is our guy! ie = explorer; } } Note : this snipet should be added somewhere where you have access to the _applicationObject. |
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
_applicationObject.Debugger.Go(false);
SHDocVw.ShellWindowsClass windows = new ShellWindowsClass();
foreach (SHDocVw.InternetExplorer explorer in windows)
{
if (explorer.LocationURL == string.Empty)
{
// this is our guy!
ie = explorer;
}
}
}
You also need to add reference to ShDocVw (Microsoft Shell And Automation Library).
Enjoy!
Етикети:
.NET,
.NET C# technologies,
C#,
Development,
ShDocVw,
Software Development,
Visual Studio
Oct 19, 2008
Touchless SDK : Very interesting and promising technology each of you guys should play with :)
| I came on this yesterday, I was bored because all the projects I am working on are to some degree "standard". No dev chalenge. I wanted to create, to do something interesting. So I started to browse CodePlex and found this SDK. Overview : Touchless SDK is a software development kit to help developers create applications which can be controlled without the standard peripheral devices (mouse, keyboard and so on). It enable you to create a applications which are controlled without the need to touch anything at all, just gestures in the air. How is this done? Well, I think there was a lot of research on this topic. We already have programs to detect motion from your video camera, why not try to extract information from those motions? This is |
The better news is that Touchless is Open Source project and can be obtained from CodePlex for free.
You can also whach a video on Touchless:
I downloaded this SDK and in less than a minute I made a small program which let's you move your cursor with fingers (I still can't find a good enough way to left and right click ;).
I hope I will have enough time this week to post this simple project so you can get deeper with Touchless as it seems promising technology to me.
Limitations:
Well every good thing has drawbacks. Don't get it wrong. Touchless isn't the standard in this area. It has problems (however I think after it is open source a lot of people can work on it and improve it).
So what are the limitations?
First of all - Touchless is very very very sensitive to light and to colors. It is because the way it works. In order to work, you need to specify a "marker". Marker is the thing the program looks for. So if you have a red tape on your finger and define it as marker, you will be able to command your computer with it. But if there is a object with the same color on the screen and this object is about the same size, it may be found as another marker.
The second problem (at least for the sample project I did) is that most web cameras are not sensitive enough. They are (most of them offcourse) with 640 x 480 pixels resolution. If you are about to move your cursor and your screen resolutions is 1280 x 1024 you will be only able to move the cursor 640 pixels horizontally and 480 pixels vertically (this can be software corrected by moving the cursor 3 or 4 pixels on each pixel that comes from the camera but for sensitive operations (resizing, drawing) it will not be good enough.
However I think the things above will be resolved and we will have another great way to use our computers for almost no extra charge.
I do really wish those guys luck and I will definatelly watch how this project goes and even if I can I will help a bit.
I really fell in love with this toy!
Oct 7, 2008
One more ASP.NET page optimization ...
| I wrote two articles on this topic already. The first was that you can earn few bytes from renaming the "javascript:__doPostBack" to "__dp". Then I noticed that I have problems with this. The problem was that in some cases you need to have the "javascript:" prefix. So my first attempt to do some optimization is considered more unsuccessful than successful. Now I am going to propose another way. It is again based on removing / renaming / moving existing things in the page so they can be a bit more optimized. Let's suppose we have a GridView. We clicked on the "Auto Format" thing and we not only have a GridView, but we have a nice looking grid view. It's great, but it seems to be unefficient. It appears that the GridView will add a |
I did a small snipet to fix this (not the best solution again but should be kind of starting point).
Here is my code:
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
this.EnsureChildControls();
base.Render(htmlWriter);
string html = stringWriter.ToString();
AnalyzeStyles(html);
html = RepairStyles(html);
writer.Write(html);
}
private void AnalyzeStyles(string html)
{
MatchCollection CSSMatch = Regex.Matches(html, "style=[\"].+?[\"]", RegexOptions.IgnoreCase);
foreach (Match mCss in CSSMatch)
{
if (htDuplicates.ContainsKey(mCss.Value))
{
htDuplicates[mCss.Value] = Convert.ToInt32(htDuplicates[mCss.Value]) + 1;
}
else
{
htDuplicates.Add(mCss.Value, 0);
}
}
}
private string RepairStyles(string html)
{
int classID = 0;
int pos;
IDictionaryEnumerator iOccurences = htDuplicates.GetEnumerator();
this.CSS += "";
InformaticsWeb.Pages.Optimized master = (InformaticsWeb.Pages.Optimized)this.Master;
pos = Regex.Match(html, "", RegexOptions.IgnoreCase | RegexOptions.Singleline).Index + "".Length;
html = html.Insert(pos, CSS);
return html;
}
Please note : AnalyzeStyles adds each of the style="" found on the page (each unique). If it finds secound and third and so on - it increases a counter. The counter is not currently used, but may be later used to decide which of the styles should be converted to CSS classes.
So this code basically takes the page and moves all the style="" attributes in the head section as a CSS classes. I tested and my grid view seems as beautiful as before this code was applied.
Now, does it worth to add this logic?
Well I think you can achieve the same functionality by using Skin files. I am adding this more for reference.
I also did a small excel diagram to show you how much bytes are saved based on the count of the items in the GridView:
Please note that the htDupplicates is a Hashtable, declared as a global variable, so you will need to add it if you want to use this code.
Let me now explain the columns in the excel file shown above.
The “Columns” column displays how much columns does the GridView render. Typically the columns are rendered as a table cells and doesn’t contain any style=”” attributes (at least I couldn’t see any), so this is something you can’t affect. The thing that this optimization affects is the number of rows in your gridview. The more rows you have the more bytes you will get.
The second column displays the number of rows in the grid view.
The third column is the optimized size of the gridview (when the above technique is applied).
The “Size Original” column displays the size for unoptimized page (the same page!).
And the last column shows you the difference before and after.
You can see it in the diagram - for 20 items you have about 842 bytes difference. While for 80 you have about 3,512 (I don’t think there is a live site which displays 80 items at once in a grid view ;).
Oct 6, 2008
Very elegant way to cut few more bytes from your ASP.NET markup and optimize your bandwidth a bit (2) - Solving the puzzle
| As I mentioned in my previous post, I ocassinally received errors when replacing the "javscript:__doPostBack" with "_dpb". It saved few bytes, yes, but for example the ASP Menu stopped working. I finally found what was causing the problem. It is because of links (rendered as "a href"). The ASP Menu renders them as a href="javscript:__doPostBack()". If you remove the "javascript:" part you will have problems as the browser will not be able to understand that you are trying to call a JS function. A possible solution is to move the call to the OnClick of the "a" element, leaving "#" in the "href" attribute like this: a href="#" onclick="_dpb()" This will however cause a small side effect. When the user clicks on the first |
Conclusion : You can apply the above technique but it will not help you much and I think it involves to much efforts for a small effect (few bytes). If you really want to get this benefit you can replace the "javascript:__doPostBack" with "javascript:_dp" and you will get less bytes than if removing the "javascript:" part but the page will work as expected.
I am currently working on other techniques to cut more of the ASP page markup, but they are a bit more serious. I hope I will write another post soon to inform you how it is going.
Етикети:
.NET,
.NET C# technologies,
ASP.NET newbies,
Development
Oct 3, 2008
Very elegant way to cut few more bytes from your ASP.NET markup and optimize your bandwidth a bit
| I was thinking about how can I optimize the markup of a page a bit. I found a great way (great but not very very very efficient) to do so. It is based on a strategy that came in my mind recently. Let's think a bit. We already have very interesting methods to cut bandwith of an ASP.NET page like for example compressing the view state and so on and so on. So provided we already have applied those techniques, if we still want to optimize what should we do? I call my method : iterative profit, you will soon understand why ... If we have something that repeats few times in the markup and is relatively long as name, if we make it shorter we should win some bytes right? And if the page is big enough and "the thing" is repeated more times, we |
So each time we cut the name of something, we win few bytes.
The next question is what can we cut in order to optimize our page?
What is the thing that repeats in each web control?
The answer is the "__doPostBack" function. I tried to replace it during the Rendering of the page and was able to cut a bit of the page size, while keeping the source relatively clean of errors (please note the word "relatively").
Here is a sample code:
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
html = html.Replace("\"javascript:__doPostBack", "\"__dpb");
writer.Write(html);
}
I had some issues I haven't yet identified, as I was in a rush to post this as it seems to me a brand new way to optimize pages - to look for repeating elements and cut their names... (I will be happy if there are volunteers to help with this one ;)...
Other things : DoPostBackWithOptions should also be replaced by dpbw for example, this will be done in the future, after I clean the _doPostBack as it still have few problems.
And some more things - we may consider optimizing some of the ASP.NET controls which are known to be "markup unoptimized" like the treeview, gridview for example (At least I think there may be some things in them to optimize).
Any comments are welcome.
Етикети:
.NET,
ASP.NET newbies,
Development,
Software Development
Aug 14, 2008
Skype4COMLib and Blogger - get your posts as a mood text in skype (or do whatever you want with skype ;).
My dear friend Bobby is going on vacation today at 6 p.m. Since I’m going to miss her while she’s taking her vacation on Black Sea I decided to play a bit with Skype4COM and write a small program for her.
Well I am not going to explain you how I did this. I got better idea later. I decided to make a mood changer for me. The mood changer will take my blogger posts and rotate them as skype mood text.

First of all, where should I get my posts from? Well, there are two ways I can think of. The first one is to use the Blogger API (login with the user, get all user blogs, get all user posts, etc.).
The second one is to use the RSS feed that blogger automatically creates for each blog.
Since this is very small tool I think the first approach is too “heavy” and “complex”. After all we aren’t going to post to the blog or anything that will require us to login in Blogger. So I took the RSS approach.
Let’s see how you can create a small program to do this for you:
1. Start new windows application.
2. Right click your References folder in the solution explorer and choose Add Reference …
3. In the dialog box click on the “COM” tab and find Skype4COMLib.
4. Click OK.
Now you have that skype thing referenced in your project. Add it to your using clause:
using SKYPE4COMLib;
After we are here, and we know we are going to use RSS, we will need Xml namespace as well. Add it too:
using System.Xml;
Okay. In my approach, I wanted to display random post on every 10 seconds. This means I will need to store a post title -> post link pair somewhere. I did this in a generic List of string[] arrays. I am not quite sure how optimized is this but this is only sample and it works fine for me. If you can think of something more optimized - please do not hesitate to write a comment ;). For now, however, add the System.Collections namespace to your using clause:
using System.Collections;
Okay, we have everything we will need to create our small tool. Now add a timer on your form. It’s timer1 in my sample. Set it's interval to 10000 (10 seconds).
Add the following global variables to your project:
List<string[]> posts = new List<string[]>();
private SKYPE4COMLib.Skype skype;
Here is how your Form_Load event should look like:
private void Form1_Load(object sender, EventArgs e)
{
skype = new SkypeClass();
this.WindowState = FormWindowState.Minimized;
GetBlogs();
timer1.Enabled = true;
}
What I want you to note in the Page_Load is that I am assigning the skype variable. This way it will remain linked to your skype until the program is runned.
I used routine GetBlogs() in this project, here is it:
private void GetBlogs()
{
XmlDocument docRSS = new XmlDocument();
docRSS.Load("http://donchevp.blogspot.com/feeds/posts/default?alt=rss");
foreach (XmlNode nodeItem in docRSS.SelectNodes("/rss/channel/item"))
{
string title = nodeItem.SelectSingleNode("title").InnerText;
string href = nodeItem.SelectSingleNode("link").InnerText;
posts.Add(new string[] { href, title });
}
}
NOTE: replace the url in the docRSS.Load() method, otherwise you will promote my blog ;).
This routine simply takes all the posts and stores them in the List of string arrays as link, title pairs.
Now we need to display the posts as title “-“ link. This will happen in the timer1_Tick event:
private void timer1_Tick(object sender, EventArgs e)
{
int iPostIndex = int.MinValue;
if (posts.Count > 0)
{
Random rnd = new Random();
iPostIndex = rnd.Next(0, posts.Count);
skype.CurrentUserProfile.MoodText = posts[iPostIndex][1] + " - " + posts[iPostIndex][0];
}
}
Everything seems to work fine now. Run your program. Skype should ask you if you are sure you want to give access to this program to use skype. Agree with that. You should now see your posts rotating each 10 seconds.
Here is the complete code (I will also upload the project on Chameleon Bulgaria site, as codes in Blogger doesn’t appear very smoothly):
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SKYPE4COMLib;
using System.Xml;
using System.Collections;
namespace dayOffCounter
{
public partial class Form1 : Form
{
List<string[]> posts = new List<string[]>();
private SKYPE4COMLib.Skype skype;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
skype = new SkypeClass();
this.WindowState = FormWindowState.Minimized;
GetBlogs();
timer1.Enabled = true;
}
private void GetBlogs()
{
XmlDocument docRSS = new XmlDocument();
docRSS.Load("http://donchevp.blogspot.com/feeds/posts/default?alt=rss");
foreach (XmlNode nodeItem in docRSS.SelectNodes("/rss/channel/item"))
{
string title = nodeItem.SelectSingleNode("title").InnerText;
string href = nodeItem.SelectSingleNode("link").InnerText;
posts.Add(new string[] { href, title });
}
}
private void timer1_Tick(object sender, EventArgs e)
{
int iPostIndex = int.MinValue;
if (posts.Count > 0)
{
Random rnd = new Random();
iPostIndex = rnd.Next(0, posts.Count);
skype.CurrentUserProfile.MoodText = posts[iPostIndex][1] + " - " + posts[iPostIndex][0];
}
}
}
}
Things to consider: Unfortunately skype has some constraints we can not avoid. First of all - the text seems to be too short to hold some of my posts, which results in links not being rendered correctly and leading to a wrong page (or even worse - to a page that doesn’t exist). I really wish to be able to set click here links as a mood text but it is not possible for now (at least I couldn’t find such functionality).
Happy codding!
| This is where everything started ;) (thanks, Bobby for the inspiration ;). She had her skype mood text set to how many days are until her vacation takes place. I wanted to help her so I wrote a simple tool to countdown until 6 p.m. and change her Skype mood accordingly. |
Well I am not going to explain you how I did this. I got better idea later. I decided to make a mood changer for me. The mood changer will take my blogger posts and rotate them as skype mood text.
First of all, where should I get my posts from? Well, there are two ways I can think of. The first one is to use the Blogger API (login with the user, get all user blogs, get all user posts, etc.).
The second one is to use the RSS feed that blogger automatically creates for each blog.
Since this is very small tool I think the first approach is too “heavy” and “complex”. After all we aren’t going to post to the blog or anything that will require us to login in Blogger. So I took the RSS approach.
Let’s see how you can create a small program to do this for you:
1. Start new windows application.
2. Right click your References folder in the solution explorer and choose Add Reference …
3. In the dialog box click on the “COM” tab and find Skype4COMLib.
4. Click OK.
Now you have that skype thing referenced in your project. Add it to your using clause:
using SKYPE4COMLib;
After we are here, and we know we are going to use RSS, we will need Xml namespace as well. Add it too:
using System.Xml;
Okay. In my approach, I wanted to display random post on every 10 seconds. This means I will need to store a post title -> post link pair somewhere. I did this in a generic List of string[] arrays. I am not quite sure how optimized is this but this is only sample and it works fine for me. If you can think of something more optimized - please do not hesitate to write a comment ;). For now, however, add the System.Collections namespace to your using clause:
using System.Collections;
Okay, we have everything we will need to create our small tool. Now add a timer on your form. It’s timer1 in my sample. Set it's interval to 10000 (10 seconds).
Add the following global variables to your project:
List<string[]> posts = new List<string[]>();
private SKYPE4COMLib.Skype skype;
Here is how your Form_Load event should look like:
private void Form1_Load(object sender, EventArgs e)
{
skype = new SkypeClass();
this.WindowState = FormWindowState.Minimized;
GetBlogs();
timer1.Enabled = true;
}
What I want you to note in the Page_Load is that I am assigning the skype variable. This way it will remain linked to your skype until the program is runned.
I used routine GetBlogs() in this project, here is it:
private void GetBlogs()
{
XmlDocument docRSS = new XmlDocument();
docRSS.Load("http://donchevp.blogspot.com/feeds/posts/default?alt=rss");
foreach (XmlNode nodeItem in docRSS.SelectNodes("/rss/channel/item"))
{
string title = nodeItem.SelectSingleNode("title").InnerText;
string href = nodeItem.SelectSingleNode("link").InnerText;
posts.Add(new string[] { href, title });
}
}
NOTE: replace the url in the docRSS.Load() method, otherwise you will promote my blog ;).
This routine simply takes all the posts and stores them in the List of string arrays as link, title pairs.
Now we need to display the posts as title “-“ link. This will happen in the timer1_Tick event:
private void timer1_Tick(object sender, EventArgs e)
{
int iPostIndex = int.MinValue;
if (posts.Count > 0)
{
Random rnd = new Random();
iPostIndex = rnd.Next(0, posts.Count);
skype.CurrentUserProfile.MoodText = posts[iPostIndex][1] + " - " + posts[iPostIndex][0];
}
}
Everything seems to work fine now. Run your program. Skype should ask you if you are sure you want to give access to this program to use skype. Agree with that. You should now see your posts rotating each 10 seconds.
Here is the complete code (I will also upload the project on Chameleon Bulgaria site, as codes in Blogger doesn’t appear very smoothly):
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SKYPE4COMLib;
using System.Xml;
using System.Collections;
namespace dayOffCounter
{
public partial class Form1 : Form
{
List<string[]> posts = new List<string[]>();
private SKYPE4COMLib.Skype skype;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
skype = new SkypeClass();
this.WindowState = FormWindowState.Minimized;
GetBlogs();
timer1.Enabled = true;
}
private void GetBlogs()
{
XmlDocument docRSS = new XmlDocument();
docRSS.Load("http://donchevp.blogspot.com/feeds/posts/default?alt=rss");
foreach (XmlNode nodeItem in docRSS.SelectNodes("/rss/channel/item"))
{
string title = nodeItem.SelectSingleNode("title").InnerText;
string href = nodeItem.SelectSingleNode("link").InnerText;
posts.Add(new string[] { href, title });
}
}
private void timer1_Tick(object sender, EventArgs e)
{
int iPostIndex = int.MinValue;
if (posts.Count > 0)
{
Random rnd = new Random();
iPostIndex = rnd.Next(0, posts.Count);
skype.CurrentUserProfile.MoodText = posts[iPostIndex][1] + " - " + posts[iPostIndex][0];
}
}
}
}
Things to consider: Unfortunately skype has some constraints we can not avoid. First of all - the text seems to be too short to hold some of my posts, which results in links not being rendered correctly and leading to a wrong page (or even worse - to a page that doesn’t exist). I really wish to be able to set click here links as a mood text but it is not possible for now (at least I couldn’t find such functionality).
Happy codding!
Етикети:
.NET C# technologies,
C#,
Development,
Google Blogs API,
Skype,
Skype4COM,
Software
Jul 17, 2008
Code Policies - the first step to get rid of boring code policy violations is made.
| As I and Vesko (only!) discussed - it is great to follow code policies, and they are saving time. A lot of time. I agree. I really like to have so strict policies at work so I can find for example the ObjectDataSource of some dropdown, without knowing its name. For example i will type "objDsSomething" or "odsSomething" or "ODSSomething". It really saves time. I don't really agree with Vesko's opinion that only in the begining you are violating the code policies. I think even developers who worked on the same project for year will violate its policies (not so often offcourse). The problem is that we are all human beings and we all make mistakes. I decided to do something to help myself get rid of at least the boring code policies - such |
Here is what I have so far (I started this thing few days ago and I am working on it for about an hour daily after I was all day at work so it may not look very promising but I think it has potential):
When you click on "Validate Current Document" the document which is currently open will be validated against predefined naming conventions. If you violated something you will have this output:
I have few more problems to solve and will be really glad if someone can point me the direction:
1. I need to find a way to add this menu to the context menu for the document and also I would like to add hot key so you can for example validate the document by pression "CTRL + V + D" or something else (this is low priority).
2. I would also like to be able to check the code itself for inadequate assignments, method calls and so on. The CodeModel approach I think, will not allow me to do so.
3. I would like to change those standard icons with custom ;) (low priority).
Currently this thing can fly only for naming conventions.
Jul 13, 2008
Code policies?
| I was thinking the other day about how much efforts does it take to strictly follow your company code policies. They are saving time for sure, but they are also wasting time. First of all the developer needs to think about the policies all the time. This districts him/her from the real problems. Second - after the task is completed the developer again needs to check if his / her code follows the code policies. Third - if there is a code review - the code reviewer will also need to check if there isn't a problem with those code policies, class by class, member by member. Some of the rules are very very foundamental as for example not to reference the DataAccess Layer from the User Interface Layer. Other are company level rules - such as |
While some of the things aren't very easy to note in a code, other are obvious. And while some of the things aren't very easy to automate via AddIn or external program, other can be easilly automated.
In my opinion the developer should be focussed develop some more useful functionality, instead thinking about which rule will he / she broke.
Please note that by writing the above sentence I am not saying - "Drop the code policies!", but "Automate the code policies!". If I had some tool to check if I violate a rule while writing code, I will rewrite my code in order to satisfy this rule. But after I don't have I need to think about those rules while developing, which districts me from what I need to achieve.
I would really appreciate if you drop a comment on the following question(s):
"Does the code policy bother you? Does it take from your time? Does it districts you?"
Thanks in advance!
Mar 19, 2008
Very simple tool to watch ending Sedo Auctions
| Few months ago I was interested in the domain trading business. It was interesting to me as it generated 14.2 million dollars back in 2006. It is based on speculla I think. Something like FOREX but not quite. I registered two domains and placed them on Sedo Auctions. I was also interested on how other domains are going so I decided to write a small tool. It will stay in your tray and will show you the auctions which are about to end the next 24 hours. The following information is gathered about each auction: - Domain for sale - Price - Currency - Time left before the auction is closed - Google PR for each domain The program is available for download from Chameleon Bulgaria I decided to put a banner on this program so my domains |
Here is a direct link to the program page on Chameleon Bulgaria may be found
here
Feb 29, 2008
5 minutes C# to build a Zoo with Marker Interfaces.
| First of all what is marker interface? A marker interface is an empty interface which defines no fields, but is only there for reference. Let's start with the case study and we will go through the example and explain everything. Case Study : Build a simple Zoo program. You have a Zoo with few animals - those animals are only fishes and birds. As this Zoo is relatively small it has only one employee to feed all the animals with the appropriate food. The fishes eat food which we will refer to as "fishfood" and the birds eat a food which we will refer to as "grains". To accomplish this we may create an interface, which identifies the things that are common for both types of animals in the Zoo. IAnimal.cs using System; using |
using System.Text;
namespace MarkerInterface.Objects
{
interface IAnimal
{
void Feed(FoodType food);
bool Hungry
{
set;
get;
}
}
}
Ok, we gave the animals the ability to eat, but how will the employee identify what kind of food to feed them with?
Let's first define an enumerator to hold the food types:
Food.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace MarkerInterface.Objects
{
public enum FoodType
{
Grains,
Fishfood
}
}
Ok, we have the food types now. In order to split the animals in the Zoo in two separate groups we are going to use the Marker Interface, we will define two interfaces to mark which animal is fish and which is bird.
IBird.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace MarkerInterface.Objects
{
interface IBird : IAnimal
{
}
}
Now let's do the same for the fieshes:
using System;
using System.Collections.Generic;
using System.Text;
namespace MarkerInterface.Objects
{
interface IFish : IAnimal
{
}
}
Now let's have two concrete animals - one for each type:
Heller.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace MarkerInterface.Objects.Animals
{
class Heller : IFish
{
#region IFish Members
private bool hungry = false;
public void Feed(FoodType food)
{
if (food != FoodType.Fishfood)
{
throw new ArgumentException("Heller is a fish and eats only fishfood.");
}
else
{
this.hungry = false;
}
}
#endregion
#region IAnimal Members
public bool Hungry
{
get
{
return this.hungry;
}
set
{
this.hungry = value;
}
}
#endregion
}
}
Chicken.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace MarkerInterface.Objects.Animals
{
class Chicken : IBird
{
#region IBird Members
bool hungry = false;
public void Feed(FoodType food)
{
if (food != FoodType.Grains)
{
throw new ArgumentException("The chicken only eats grains.");
}
else
{
this.hungry = false;
}
}
public bool Hungry
{
get { return this.hungry; }
set { this.hungry = value; }
}
#endregion
}
}
Let's have one employee to feed the animals:
ZooEmployee.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace MarkerInterface.Objects
{
class ZooEmployee
{
public delegate void OnAnimalFeeded(string Animal, string FoodType);
public event OnAnimalFeeded AnimalFeeded;
public void FeedAnimals(List<IAnimal> animals)
{
foreach (IAnimal animal in animals)
{
if (animal is IFish)
{
animal.Feed(FoodType.Fishfood);
this.AnimalFeeded(animal.GetType().Name, "fish food");
}
if (animal is IBird)
{
animal.Feed(FoodType.Grains);
this.AnimalFeeded(animal.GetType().Name, "grains");
}
}
}
}
}
NOTE: I added the OnAnimalFeeded delegate and the AnimalFeeded event, so the Zoo employee can report to us when it has feeded an animal.
Let's define the Zoo class:
Zoo.cs
namespace MarkerInterface.Objects
{
class Zoo
{
List<IAnimal> animals = new List<IAnimal>();
List<ZooEmployee> employees = new List<ZooEmployee>();
public Zoo()
{
animals.Add(new Animals.Chicken());
animals.Add(new Animals.Heller());
ZooEmployee employee = new ZooEmployee();
this.employees.Add(employee);
}
public List<IAnimal> Animals
{
get { return this.animals; }
}
public List<ZooEmployee> Employees
{
get { return this.employees; }
}
}
}
Now, in the main form of the program we will instantiate the Zoo class, and call its employee to feed all the animals.
On the form I added one button and one RichTextbox. When I click the button the following code will get executed:
Objects.Zoo zoo = new MarkerInterface.Objects.Zoo();
zoo.Employees[0].AnimalFeeded += new MarkerInterface.Objects.ZooEmployee.OnAnimalFeeded(Form1_AnimalFeeded);
zoo.Employees[0].FeedAnimals(zoo.Animals);
What are we doing here - we are simply creating a Zoo, we are using it's first employee (as we said it will always be exactly one emplyee) AnimalFeeded event to report when what animal is feeded and with what food and we are then asking the employee to feed the animals.
The marker interfaces here are used in the ZooEmployee.FeedAnimals() method to help the employee decide which type of food to give to each animal.
As the Chicken inherits from the IBird the employee will feed it with grains. As the Heller inherits from IFish it will be feeded with fish food.
Here is the Form1_AnimalFeeded which is fired each time the employee feeds animals. It will be used to display in the RichTextBox what is our employee doing at the moment:
void Form1_AnimalFeeded(string Animal, string FoodType)
{
this.rtbAnimalsFeeded.AppendText(Animal + " was feeded with " + FoodType + "\n");
}
Here is how it looks like after it was runed:
Hope you understood it ;).
Feb 9, 2008
sealed class usage
| We recently started an internal academy in our company to improve our software development skills. The first meeting was about OOP fundamentals, it was really interesting (thanks Vesko for your efforts!). This question appeared as interesting for me - when should we use the sealed class. Some collegues guessed it should be used in the most concrete classes, as they will not be used as a base classses, but I don't think so. After all - why should you say : "Hey, don't use this thing as a base class" explicitly after you know it will not be used anyway. I did soem research on the net about the sealed class usage, it appeared it's common use is for classes with static methods. The example I've found was about Brush and Pen .NET |
So when you are doing software you may keep in mind that you have that sealed thing to help you limit the inheritance of your classes.
Етикети:
.NET,
.NET C# technologies,
C#,
Development,
Software,
Software Development
Jan 13, 2008
Another 5 minutes with C# to post to Google Blogs (Blogger.com) using Google Blogs SDK (2)
Subscribe to:
Posts (Atom)