European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Free ASP.NET Hosting - HostForLIFE.eu :: How to Store Custom Objects in web.config

clock April 28, 2015 05:54 by author Rebecca

Normally, you used to have some data in appSettings section of web.config and read it when required. That is in string form, but there are lot more than this and you can update the data in web.config programmatically as well. You can store some object of custom type in web.config as well, which you normally don’t do it. But this can be very useful in several scenarios.

Have anyone tried to update some value or add some value in web.config? In this post, I'm going to tell you about web.config and how you can store the costum objects in web.config.

First, this is very common to have some constant data at appSettings section of web.config and read it whenever required. This is the way how to read data at appSettings:

//The data is stored in web.config as

<appSettings>

        <add key="WelcomeMessage" value="Hello All, Welcome to my Website." />

</appSettings>

// To read it
string message = ConfigurationManager.AppSettings["WelcomeMessage"];

If you want to update some data of appSettings programatically, you can do like this.

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings["WelcomeMessage"].Value = "Hello All, Welcome to my updated site.";
        config.Save();


If you want to add some data in appSettings, you can add some app.config data as below:

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings.Add("ErrorMessage", "An error has been occured during processing this request.");
        config.Save();


The above code is adding one new key value pair in web.config file. Now this can be read anywhere in the application.

Now, the question is, Can we store some custom data at config? The answer is YES! We can store some object. Let’s see how:

In this example, I have saved an object of my custom class NewError in web.config file. And also updating it whenever required.
To do this, Follow the below steps.

Step 1

Create a Class that inherit From ConfigurationSection (It is available under namespace System.Configuration ). Every property must have an attribute ConfigurationProperty, having attribute name and some more parameters. This name is directly mapped to web.config. Let’s see the NewError class:

public class NewError:ConfigurationSection
{
    [ConfigurationProperty ("Id",IsRequired = true)]
    public string ErrorId {
        get { return (string)this["Id"]; }
        set { this["Id"] = value; }
    }
    [ConfigurationProperty("Message", IsRequired = false)]
    public string Message {
        get { return (string)this["Message"]; }
        set { this["Message"] = value; }
    }
    [ConfigurationProperty("RedirectURL", IsRequired = false)]
    public string RedirectionPage
    {
        get { return (string)this["RedirectURL"]; }
        set { this["RedirectURL"] = value; }
    }
    [ConfigurationProperty("MailId", IsRequired = false)]
    public string EmailId
    {
        get { return (string)this["MailId"]; }
        set { this["MailId"] = value; }
    }
    [ConfigurationProperty("DateAdded", IsRequired = false)]
    public DateTime DateAdded
    {
        get { return (DateTime)this["DateAdded"]; }
        set { this["DateAdded"] = value; }
    }
}

You can see every property has attribute ConfigurationProperty with some value. As you can see the property ErrorId has attribute:

[ConfigurationProperty ("Id",IsRequired = true)]

it means ErrorId will be saved as Id in web.config file and it is required value. There are more elements in this attribute that you can set based on your requirement.
Now if you’ll see the property closely, it is bit different.

public string ErrorId {
get { return (string)this["Id"]; }
set { this["Id"] = value; }
}

Here the value is saved as the key “id”, that is mapped with web.config file.

Step 2

Now you are required to add/register a section in the section group to tell the web.config that you are going to have this kind of data. This must be in and will be as:

<section name="errorList"  type="NewError" allowLocation="true"

     allowDefinition="Everywhere"/>

Step 3

Now one can add that object in your config file directly as:

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="[email protected]" ></errorList>

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="[email protected]" ></errorList>

Step 4

And to read it at your page. Read it as follows:

NewError objNewError = (NewError)ConfigurationManager.GetSection("errorList");

And also a new object can be saved programmatically as

NewError objNewError = new NewError()
       {
         RedirectionPage="www.rediff.com",
         Message = "New Message",
         ErrorId="0",
         DateAdded= DateTime.Now.Date
       };
       Configuration config =
           WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

       config.Sections.Add("errorList", objNewError);
       config.Save();


Even one can add a custom group and have some custom elements in in this section. ASP.NET provides very powerfull APIs to read/edit the web.config file easily.

Free ASP.NET Hosting
Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET Hosting - HostForLIFE.eu :: Calling ASP.NET Page Methods using AJAX

clock April 21, 2015 06:19 by author Rebecca

In this post, I tell you how to invoke an ASP.NET page method directly from your own AJAX library. A Page method is a method that is written directly in a page. It is generally called when the actual page is posted back and some event is raised from the client. The pageMethod is called directly from ASP.NET engine. To implement PageMethod, first you need to annotate our method as WebMethod. A WebMethod is a special method attribute that exposes a method directly as XML service.

Here are the steps to create the application:

Step 1

Start a new ASP.NET Project.

Step 2

Add JQuery to your page. Then, you can add a special JQuery plugin which stringify a JSON object. And post the codes like below :

(function ($) {
$.extend({
toJson: function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
// extend plugin scope
$.fn.extend({
toJson: $.toJson.construct
});
})(jQuery);

The code actually extends JQuery to add a method called toJSON to its prototype.

Step 3

Add the server side method to the Default.aspx page. For simplicity, you can actually return the message that is received from the client side with some formatting.

[WebMethod]
public static string DisplayTime(string message)
{
// Do something

return string.Format("Hello ! Your message : {0} at {1}", message, DateTime.Now.ToShortTimeString());
}


You should make this method static, and probably should return only serializable object.

Step 4

Add the following Html which actually puts one TextBox which takes a message and a Button to call server.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Write Your message Here : <input type="text" id="txtMessage" />
</p>
<p>
<input type="button" onclick="javascript:callServer()" value="Call Server" />
</p>
</asp:Content>


Once you add this html to your default.aspx page, add some javascript to the page. We add the JQuery and our JSONStringify code to it.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/JSONStringify.js" type="text/javascript"></script>

<script type="text/javascript">
function callServer() {
var objdata = {
"message" : $("#txtMessage").val()
};
$.ajax({
type: "POST",
url: "Default.aspx/DisplayTime",
data: $.toJson(objdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, ajaxOptions) {
alert(xhr.status);
}
});
}
</script>


The above code actually invokes a normal AJAX call to the page. You can use your own library of AJAX rather than JQuery to do the same.

Hope it works for you!

Free ASP.NET Hosting

Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET Hosting - HostForLIFE.eu :: How to Discover if Linked List contains Loops or Cycles in C# ?

clock April 17, 2015 07:11 by author Peter

In this post i will be able to show you how to discover loop in linked list with ASP.NET C#. We can notice the loop within the coupled list via Floyd’s Cycle-Finding formula, explained here. The method is pretty simple: We have a tendency to begin at the start of the linked list with 2 pointers. The primary pointer is incremented through every node of the list. The second pointer moves twice as quick, and skips each other node. If the coupled list contains a loop, these 2 pointers can eventually meet at the same node, so indicating that the linked list contains a loop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
namespace Algo
{
    public class Node
    {
        public Node Next { get; set; }
        public int Value { get; set; }
        public Node(int value)
        {
            this.Value = value;
        } 
    }
    public class LinkedList
    {        
    private Node _head;
        public LinkedList()
        { 
        }
        public void AppendLast(Node newNode)
        {
            if (_head == null)
            {
                _head = newNode;
            }
            else
            {
                Node current = _head;
                while (current.Next != null)
                {
                    current = current.Next;
                }
                current.Next = newNode;
            }
        }
        public override string ToString()
        {
            Node current = _head;
            StringBuilder builder = new StringBuilder();
            while (current != null)
            {
                builder.Append(current.Value + "->");
                current = current.Next;
            }
            return builder.ToString();
        }
        public bool IsCycle()
        {
            Node slow = _head;
            Node fast = _head;
            while (fast != null && fast.Next != null)
            {
                fast = fast.Next.Next;
                slow = slow.Next;
                if (slow == fast)
                    return true;
            }
            return false; 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LinkedList list = new LinkedList();
            list.AppendLast(new Node(10));
            list.AppendLast(new Node(20));
            list.AppendLast(new Node(30));
            Node cycle = new Node(40);
            list.AppendLast(cycle);
            list.AppendLast(new Node(60));
            list.AppendLast(cycle);
             if (list.IsCycle())
            {
                Console.WriteLine("Linked List is cyclic as it contains cycle or loop");
            }
            else
            {
                Console.WriteLine("LinkedList is not cyclic, no loop or cycle found");
            }   
        }
   }
}

Free ASP.NET Hosting

Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in