Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 1 March 2012

ProgrammerFail - Else or Continue?

 

if (value < 100)
{
    value = 100 - value;
    continue;   // Why???
}
else
{
    value = value + 100;
}
Double penetration – I really don’t want to run the else clause…

ProgrammerFail

!!!FAIL!!!

Thursday, 9 February 2012

ProgrammerFail–The Fail of Naming

 

 

if (!need_to_update)
    update_all_views();

Let's update all the views, when there is no need to update.. As we can see high quality comments describe what this piece of shit does.

 

ProgrammerFail

!!!FAIL!!!

Tuesday, 7 February 2012

ProgrammerFail–Advanced techniques using Sql Server in C#

 

[WebMethod]
public static string CreateProfileID(string firstName, string lastName)
{
    string profileID = "";

    using (SqlConnection conn = Common.getConnection())
    {
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = string.Format("select dbo.[create-something] ('{0}', '{1}') as somethingID", firstName, lastName);

            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                profileID = dr["somethingID"] as string;
            }
        }
        catch (Exception e)
        {

        }
    }

    return profileID;
}

Everything in one method: How to handle exceptions.

 

ProgrammerFail

!!!FAIL!!!

Thursday, 2 February 2012

ProgrammerFail–Go To The Hell

 

Without any comment, let’s go to the hell:

/// <summary>
/// WriteRaw writes out the given string "unescaped", in other words it better be well formed XML markup.
/// So for the XmlNodeWriter we parse this string and build the resulting tree, so it maps to setting the
/// InnerXml property.  
/// </summary>
/// <param name="data"></param>
public override void WriteRaw(string data)
{
    if (data.IndexOf("<") < 0)
    {
        WriteString(data);
        return;
    }

    switch (state)
    {
        case WriteState.Start:
            goto case WriteState.Content;
        case WriteState.Prolog:
            goto case WriteState.Content;
        case WriteState.Element:
            state = WriteState.Content;
            goto case WriteState.Content;
        case WriteState.Attribute:
            {
                ArrayList saved = new ArrayList();
                if (ca.HasChildNodes)
                {
                    while (ca.FirstChild != null)
                    {
                        saved.Add(ca.FirstChild);
                        ca.RemoveChild(ca.FirstChild);
                    }
                }
                ca.InnerXml = data;
                for (int i = saved.Count - 1; i >= 0; i--)
                {
                    ca.PrependChild((XmlNode)saved[i]);
                }
            }
            break;
        case WriteState.Content:
            {
                ArrayList saved = new ArrayList();
                if (current.HasChildNodes)
                {
                    while (current.FirstChild != null)
                    {
                        saved.Add(current.FirstChild);
                        current.RemoveChild(current.FirstChild);
                    }
                }
                current.InnerXml = data;
                for (int i = saved.Count - 1; i >= 0; i--)
                {
                    current.PrependChild((XmlNode)saved[i]);
                }
                state = WriteState.Content;
            }
            break;
        case WriteState.Closed:
            throw new InvalidOperationException("Writer is closed");
    }

}

Nice combination of using goto and switch statement together. I hope I will never work with the author.

 

ProgrammerFail

!!!FAIL!!!

Tuesday, 27 September 2011

Not every man should be a computer programmer

 

The question is only that: Why???

 

Code Snippet
  1. catch (Exception ex)
  2. {
  3.     if ((ex.GetType().ToString() == "System.Data.SqlClient.SqlException") && ex.Message.LastIndexOf("Timeout expired") >= 0)
  4.     {
  5.        /// Secret code
  6.     }
  7.     else
  8.         throw ex;
  9. }

Why the hell he doesn’t go and play football instead of programming?

Monday, 7 February 2011

Generate RDLC dynamically with unique column headers

I use the great example from Gotreportviewer since about six month that uses Microsoft Reportviewer and my biggest problem is giving columns titles that different to field names.

There is my solution that has an additional property: List<string> Headers that contains column titles with the following restriction:

Number of headers must be equal to number of columns or TableRdlGenerator throws the following exception:
Error creating report: header and field columns must be set and have to be the same count of elements both of them!

The entire solution can be downloaded from my public folder on skydrive.

Sunday, 6 February 2011

jQuery based collapse extender web user control for asp.net

After I have been started to learn jquery I decided to replace my Ajax Control Toolkit controls for a jQuery-based solution.

My control for replace in that week is the CollapsiblePanelExtender. I need a solution that works on partial page postbacks and full page postbacks too and stores collapsed state during postbacks, and, of course I have to be able to change the collapse state on server side so I had to mix server and client side code for the solution.

Note: at the end of the post, I share the zipped full Visual Studio 2010 solution.

The extender needs the following informations:

    • Collapsed: The state if the target control collapsed or not.
    • TargetControlID: The ID of the panel that will be collapsed.
    • ToggleControlID: The ID of the control that we will click on when toggle or collapse.
    • ToggleTextID: The ID of the control that shows different texts on different states.
    • ToggleImageID: The ID of the control that show different images on different states.
    • ExpandedText: Text to show when the control is expanded.
    • CollapsedText: Text to show when the control is collapsed.
    • ExpandedImage: Image to show when the control is expanded.
    • CollapsedImage: Image to show ehen the control is collapsed.

The code behind of the web user control:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JQueryCollapse
{
    public partial class jQueryToggleExtender : System.Web.UI.UserControl
    {
        #region properties
        /// <summary>
        /// Defines if the panel to collapse is collapsed or not.
        /// </summary>
        public bool Collapsed
        {
            get
            {
                return hfCollapsed.Value == "1" ? true : false;
            }
            set { hfCollapsed.Value = (value ? 1 : 0).ToString(); }
        }

        protected string _TargetControlID;
        /// <summary>
        /// A conntrol to collapse and expand
        /// </summary>
        public string TargetControlID
        {
            protected get
            {
                return GetClientID(_TargetControlID);
            }
            set
            {
                _TargetControlID = value;
            }
        }

        protected string _ToggleControlID;
        /// <summary>
        /// A control to toggle.
        /// </summary>
        public string ToggleControlID
        {
            protected get
            {
                return GetClientID(_ToggleControlID);
            }
            set
            {
                _ToggleControlID = value;
            }
        }

        protected string _ToggleTextID;
        /// <summary>
        /// ID for toggle text control.
        /// </summary>
        public string ToggleTextID
        {
            protected get
            {
                return GetClientID(_ToggleTextID);
            }
            set
            {
                _ToggleTextID = value;
            }
        }

        protected string _ToggleImageID;
        /// <summary>
        /// ID for toggle image control
        /// </summary>
        public string ToggleImageID
        {
            protected get
            {
                return GetClientID(_ToggleImageID);
            }
            set
            {
                _ToggleImageID = value;
            }
        }

        /// <summary>
        /// Text to show when expanded
        /// </summary>
        public string ExpandedText { get; set; }
        /// <summary>
        /// Text to show when collapsed
        /// </summary>
        public string CollapsedText { get; set; }
        /// <summary>
        /// Image to show when expanded
        /// </summary>
        public string ExpandedImage { get; set; }
        /// <summary>
        /// Image to show when collapsed
        /// </summary>
        public string CollapsedImage { get; set; }
        #endregion

        /// <summary>
        /// Get a ClientID for a control by ID
        /// </summary>
        /// <param name="id">Id of the control</param>
        /// <returns></returns>
        protected string GetClientID(string id)
        {
            Control c = ControlUtils.FindControlRecursive(this.Page, id);

            return null != c ? c.ClientID : null;
        }
    }
}

In the markup we need to include our javascript files. For getting this work on partial page and full page postbacks and any other cases we rendering script block in InlineScripts as shown in my previous post before. We store collapsed state in a simple asp.net hiddenfield because we can reach it’s value on server and client side too.
Based on these the markup for the web user control is:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="jQueryToggleExtender.ascx.cs"Inherits="JQueryCollapse.jQueryToggleExtender" %>
<asp:ScriptManagerProxy runat="server" ID="smp">
    <Scripts>
        <asp:ScriptReference Path="~/js/jquery-1.4.4.min.js" />
        <asp:ScriptReference Path="~/js/jquery-ui-1.8.8.custom.min.js" />
    </Scripts>
</asp:ScriptManagerProxy>
<wc:InlineScript runat="server" ID="inlineScripts">
    <script type="text/javascript">
        function pageLoad() {
            var collapsed = $get('<%= hfCollapsed.ClientID %>');

            $('#<%= ToggleControlID %>').click(
                function () {
                    if (collapsed.value == 1) {
                        $('#<%= ToggleImageID %>').attr('src', '<%= ExpandedImage %>');
                        $('#<%= ToggleTextID %>').text('<%= ExpandedText %>');
                    }
                    else {
                        $('#<%= ToggleImageID %>').attr('src', '<%= CollapsedImage %>');
                        $('#<%= ToggleTextID %>').text('<%= CollapsedText %>');
                    }

                    $('#<%= TargetControlID %>').toggle('blind', {}, 500);
                    collapsed.value = 1 - collapsed.value;
                });

            if (collapsed.value == 1) {
                $('#<%= TargetControlID %>').hide();
                $('#<%= ToggleTextID %>').text('<%= CollapsedText %>').html();
                $('#<%= ToggleImageID %>').attr('src', '<%= CollapsedImage %>');
            } else {
                $('#<%= ToggleTextID %>').text('<%= ExpandedText %>').html();
                $('#<%= ToggleImageID %>').attr('src', '<%= ExpandedImage %>');
            }
        }
    </script>
</wc:InlineScript>
<asp:HiddenField runat="server" ID="hfCollapsed" />

We have to register our control in the web.config before using:

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
        <pages>
            <controls>
                <!--Registering inline script-->
                <add tagPrefix="wc" assembly="JQueryCollapse" namespace="JQueryCollapse.WebServerControls" />
                <!--Registering toggle extender-->
                <add tagPrefix="wuc" tagName="Toggle" src="~/WebUserControls/jQueryToggleExtender/jQueryToggleExtender.ascx" />
            </controls>
        </pages>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>

</configuration>

A simple example page for testing:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JQueryCollapse.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jquery toggle for asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel runat="server" ID="upMain">
        <ContentTemplate>
            <asp:Button runat="server" ID="btnClickMe" Text="ClickMe" />
            <a id="hrefToggle" href="#" runat="server">
                <asp:Panel ID="pnToggle" runat="server" Width="100%" BackColor="Azure">
                    <asp:ImageButton runat="server" ID="imgCollapse" AlternateText="Click here to collapse or expand" />
                    <asp:Label runat="server" ID="lblCollapse"></asp:Label>
                </asp:Panel>
            </a>
            <asp:Panel runat="server" ID="pnContent">
                Hello
            </asp:Panel>
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Button runat="server" ID="btnPb" Text="Postback" />
    <br />
    <asp:Button runat="server" ID="btnCollapse" OnClick="btnCollapse_Click" Text="Toggle" />
    <%--ToggleControlExtender--%>
    <wuc:Toggle runat="server" ID="tTest" TargetControlID="pnContent" ToggleControlID="hrefToggle"
        ToggleImageID="imgCollapse" ToggleTextID="lblCollapse" ExpandedText="Click here to collapse"
        ExpandedImage="Images/collapse.gif" CollapsedText="Click here to expand" CollapsedImage="Images/expand.gif"
        Collapsed="true"></wuc:Toggle>
    </form>
</body>
</html>

And the code behind of the page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JQueryCollapse
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Toggle the extender
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCollapse_Click(object sender, EventArgs e)
        {
            tTest.Collapsed = !tTest.Collapsed;
        }
    }
}

 

And at last the full source code of the solution can be downloaded my public folder on skydrive.

Monday, 31 January 2011

Asp.net web server control for rendering script blocks

There are many ways to add script block to our asp.net pages. This is a very simple problem until we had got a complex project with custom controls, partial page rendering, updatepanels and dynamically loaded controls.
We have to add script blocks different ways if we asynchrony post backs or full page post backs.
The other problem is when the script block don’t have to load at the first page load, it depends on some logic dynamically.

After many trying I use this solution since about half year and it works at any case.

The simple and easy to use source code is:

public class InlineScript : Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            StringBuilder sb = new StringBuilder();
            base.Render(new HtmlTextWriter(new StringWriter(sb)));

            string script = sb.ToString();

            ScriptManager sm = ScriptManager.GetCurrent(Page);
            if (!(null == sm))
            {
                if (sm.IsInAsyncPostBack)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(InlineScript), UniqueID, script, false);
                }
                else
                {
                    base.Render(writer);
                }
            }
            else
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, sb.ToString());
            }
        }
    }

After registering into web.config, we can use it easily everywhere on our program:

<wc:InlineScript ID="isTest" runat="server">
    <script type="text/javascript">
        function pageLoad() {
            alert('hi');
        }
    </script>
</wc:InlineScript>

Saturday, 8 January 2011

C#: throwable exceptions and Visual Studio Productivity Power Tools

 

There is a really great add-on for Visual Studio named Productivity Power Tools. It helps a lot during my work but hides some information that so important for me: the list of throwable exceptions.

At the university I didn’t have a choice. I had to learn Java. Java is a great language and has a restriction that I like so: you must specify the list of the throwable exceptions at the specification of each method. I work with C# nowadays. It doesn’t has this rule but Visual Studio tries to help us on a simple way: it shows us this list when we hover on the name of the given method with the mouse like this:
originalLook

As we can se, we now a bit closer to the Java restrictions. We can find out fast the given list but the language still don’t force us into handle all exceptions. It smart or not – I don’t know. But in fact I’m happy to see this list.

There is a bit problem with the power tools: It gives us a new window for our Visual Studio, named Solution Navigator. It has a lot of functions among others coloring the hints that I shown before:

withSolutionNavigator

Ops! As we can see, the list of throwable exceptions has disappeared. We have an other function instead of this, every can try this out by clicking on the triangle at the right side of the popup.

At this time we have two choice. We can use our Visual Studio with these settings or we can disable this function by setting of on the Visual Studio menu –> Tools –> Options –> Productivity Power Tools –> Solution Navigator. We got the original function after restarting our development environment.

powerToolsSettings

 

Remarks: Solution Navigator is so slow. Sometimes useful but the most part of my times it only slows down my work without any benefits.

Friday, 17 December 2010

C# object initializers: use them smart!

Object initializers came with .Net framework in 2008. Using object initializers we can easily initialize our objects fields without writing many constructors:

            // Using object initializer
            Person demoP = new Person()
            {
                ID = 0,
                Name = "Happy",
                Age = 1
            };


As we can see, this method is simple. As in the old way, we can write a constructor or set fields by hand:

            Person oldDemoP = new Person();
            oldDemoP.ID = 0;
            oldDemoP.Name = "Happy";
            oldDemoP.Age = 1;



Using object initializers, we are able to save a lot of coding. That's good, isn't it? Less coding means less work and more beer, so we happy, aren't we?

Sorry, but the answer is: Not at every cases. In the real life, we spend our work hours with creating new lines of codes only about 10% and we are debugging our code all day from morning to night. And in real life, things don't work. You have databases and objects with bad design or with good design and bad data. You think every person has Age but after 3 migrates you can find some records that don't have.
Let's take a simple object (Person):

    public class Person
    {
        public int ID { getset; }
        public string Name { getset; }
        public int Age { getset; }
    }

Person has ID, Name and Age properties.

In real life scenarios there are many case when you know that, you can get _Always_ the age of the person and at two case in the 1.5 million records you won't get it. In this way you get Exception when try assign a null value to an Age property. The question is: How does the Exception look like? What we can find in the error logs?

Presenting the problem I made a simple example. I simulated my database with a list and use a special person class with object as property types:

    public class PersonDS
    {
        public object ID { getset; }
        public object Name { getset; }
        public object Age { getset; }
    }


I used this type for making an emulated simple sample database:

            List<PersonDS> database = new List<PersonDS>();
 
            database.Add(new PersonDS() { ID = 1, Name = "Peter", Age = 18 });
            database.Add(new PersonDS() { ID = 2, Name = "Liza", Age = null });
            database.Add(new PersonDS() { ID = 3, Name = "Cloe", Age = 16 });


I. In the old way, we can set values one by one. Now, we get error at the assignment:


 // Old way to read datas
            try
            {
                List<Person> oldPersons = new List<Person>();
                foreach (var datarow in database)
                {
                    Person p = new Person();
                    p.ID = (datarow.ID as int?).Value;
                    p.Name = datarow.Name as string;
                    p.Age = (datarow.Age as int?).Value;// Throws Exception at value assignment
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Message: {1}\nStackTrace: {1}"
                    , exc.Message, exc.StackTrace));
            }


II. Using the new way, we get the Exception when initializing the object:

            // The new way to read datas
            try
            {
                List<Person> newPersons =   
                        (from p in database
                         select new Person()
                         {// Throws Exception at object initialize
                             ID = (p.ID as int?).Value,
                             Name = p.Name as string,
                             Age = (p.Age as int?).Value
                         }).ToList();
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Message: {1}\nStackTrace: {1}"
                    , exc.Message, exc.StackTrace));
            }
        }
As we can see, we get our exceptions in both cases. But at the old way, we can see that we have a missing Age value at the first look. With object initializers, we see only that we got an error at the initialize. And we have to find out what was the error exactly.
We can find many problems with this example: at the real life, I never used this form to read data from database: p.Age = (datarow.Age as int?).Value;// Throws Exception at value assignment
There are many ways to do this properly but the target is showing a simple problem with object initializers: error messages are not enough well detailed. In real life we usually don't have objects with only three properties. And we can get data with many ways: databases, xmls, streams, user input, ... 
The conclusion is: let's type a bit more but make error safe code. When we should bet our month salary for that property and want to say: 'Oh, it must be filled', don't be lazy and handle the possibility when it's not and we can sit down and open a beer.


Morzel

The entire code example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ObjectInitializersVSOldWays
{
    public class Person
    {
        public int ID { getset; }
        public string Name { getset; }
        public int Age { getset; }
    }
 
    public class PersonDS
    {
        public object ID { getset; }
        public object Name { getset; }
        public object Age { getset; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            // Using object initializer
            Person demoP = new Person()
            {
                ID = 0,
                Name = "Happy",
                Age = 1
            };
 
            Person oldDemoP = new Person();
            oldDemoP.ID = 0;
            oldDemoP.Name = "Happy";
            oldDemoP.Age = 1;
 
            List<PersonDS> database = new List<PersonDS>();
 
            database.Add(new PersonDS() { ID = 1, Name = "Peter", Age = 18 });
            database.Add(new PersonDS() { ID = 2, Name = "Liza", Age = null });
            database.Add(new PersonDS() { ID = 3, Name = "Cloe", Age = 16 });
 
            // Old way to read datas
            try
            {
                List<Person> oldPersons = new List<Person>();
                foreach (var datarow in database)
                {
                    Person p = new Person();
                    p.ID = (datarow.ID as int?).Value;
                    p.Name = datarow.Name as string;
                    p.Age = (datarow.Age as int?).Value;// Throws Exception at value assignment
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Message: {1}\nStackTrace: {1}"
                    , exc.Message, exc.StackTrace));
            }
 
            // The new way to read datas
            try
            {
                List<Person> newPersons =   
                        (from p in database
                         select new Person()
                         {   // Throws Exception at object initialize
                             ID = (p.ID as int?).Value,
                             Name = p.Name as string,
                             Age = (p.Age as int?).Value
                         }).ToList();
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Message: {1}\nStackTrace: {1}"
                    , exc.Message, exc.StackTrace));
            }
        }
    }
}
And the output is:
Message:    at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Nullable`1.get_Value()
   at ObjectInitializersVSOldWays.Program.Main(String[] args) in D:\--- Souce ---\Blog\ObjectInitializersVSOldWays\ObjectInitializersVSOldWays\Program.cs:line 41
StackTrace:    at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Nullable`1.get_Value()
   at ObjectInitializersVSOldWays.Program.Main(String[] args) in D:\--- Souce ---\Blog\ObjectInitializersVSOldWays\ObjectInitializersVSOldWays\Program.cs:line 41
Message:    at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Nullable`1.get_Value()
   at ObjectInitializersVSOldWays.Program.<Main>b__4(PersonDS p) in D:\--- Souce ---\Blog\ObjectInitializersVSOldWays\ObjectInitializersVSOldWays\Program.cs:line 54
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at ObjectInitializersVSOldWays.Program.Main(String[] args) in D:\--- Souce ---\Blog\ObjectInitializersVSOldWays\ObjectInitializersVSOldWays\Program.cs:line 52
StackTrace:    at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Nullable`1.get_Value()
   at ObjectInitializersVSOldWays.Program.<Main>b__4(PersonDS p) in D:\--- Souce ---\Blog\ObjectInitializersVSOldWays\ObjectInitializersVSOldWays\Program.cs:line 54
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at ObjectInitializersVSOldWays.Program.Main(String[] args) in D:\--- Souce ---\Blog\ObjectInitializersVSOldWays\ObjectInitializersVSOldWays\Program.cs:line 52

Thursday, 9 September 2010

How to extend DotNetNuke 5.5 settings with customs

I wanted to put some custom settings into my DotNetNuke for storing values that I can use with all custom modules what I make (for example wcf service url for my data) but I didn't want to make a new table for my custom settings in my database and of course I didn't want to type lot.

The idea is taking some settings into DotNetNuke without:
- Creating a new table
- Writing sql scripts
- Using nuke api.
- Using simple key-value pairs
- Using fresh technologies (this time DotNetNuke at 5.5)

First of all, let's search where we can store key-value pairs in the DotNetNuke database. After some search I found two suitable tables: PortalSettings and HostSettings:As we can see these tables are similar: They both has SettingName and SettingValue columns. The others are not important to us. We can use HostSettings for host level settings and PortalSettings for everything that my portals need.
At my solution, I use host settings because I need them at multiple portals. I didn't check but I think you can do similar with portal settings too. CreatedByUserID values are existing users in our portal. Default settings that set during the installation has -1 CreatedByUserID value.


Now we know where we want to put our key-value pairs, the question is: how?

After using google a bit and trying many (really many) obsolete methods I found a solution that maches for my DotNetNuke version (5.5).

Steps are:

1.: Usings. Many blogs, forums, documentations telling you what to do but you don't know a bit information: Wich namespaces do I need?
using System;
using System.Linq;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Data;

3.: We need a texbox for showing the results (markup):
<asp:Label runat="server" ID="lblSetting" BackColor="AntiqueWhite"/>

2.: Create custom host setting (C#):
var dp = DataProvider.Instance();
 
// -2 Not an existing user 
// Signature: AddHostSetting(
//      string SettingKey
//      , string SettingValue
//      , bool SettingIsSecure
//      , int createdByUserID);
dp.AddHostSetting("TestKey""TestValue"false, -2);

3.: Getting Setting value by key (C#):
lblSetting.Text = HostController.Instance.GetString("TestValue");
 
4. Open a beer and be happy :)