An easy to miss gotcha in Azure Service Fabric service with multiple listeners

Hi,

If you’ve ever worked with Azure Service Fabric, then there is a high probability that you will have a service that creates multiple listeners, either to multiple ports to accept requests from different protocols or listeners to Azure services like service bus or IotHub.

In this case, you might have to create multiple communication listeners in your application. While doing this, there is a chance that you might miss one small thing which would eventually result in you getting the following error in the Service Fabric Explorer

As you can see in the error message, it says that a Unique name must be specified for each listener when multiple listeners are used. We can specify this name as the second parameter of ServiceInstanceListener class as shown below.

This will solve the error.

Hope this helps!

Check if service bus topic/subscription/queue exists with SAS key not having Manage permission

Hi,

Consider a scenario where you’ve developed an application health monitoring type system which validates your application at application startup/periodically. Now as part of that if your application uses Azure service bus queues, topics, subscriptions, then it would be good to verify that they all exist before your application actually starts its work.

So your initial thought would be to use NamespaceManager class from the Microsoft.ServiceBus assembly. This class provides <entity>Exists() methods for all the above. However, one point to note here is that NamespaceManager class requires Manage permission to be present to the SAS key from the connection string.

As a security measure, the general advise is to NOT use a SAS key with manage permission and to use one with Send/Listen permissions.

1

So for checking if the entities exist, we can use the TopicClient, SubscriptionClient, QueueClient classes from Microsoft.ServiceBus.Messaging assembly. Check below code. Click for full size image.

2_updated

 

In the above snippet, each of the .Peek() (Or PeekAsync()) methods will throw an exception (Entity not found) if the corresponding entity doesn’t exist and passes if they exist. This check can be used to determine if the entities exist or not.

P.S: There are other ways too but this is relevant if you do not want to send/receive from these service bus entities.

Hope this helps!

Resolving “CloudConfigurationManager does not exist in the current context” compiler error

Hi,

In case you get are trying to access the cloud configuration file in your Azure Cloud service and get the error “CloudConfigurationManager does not exist in the current context” on CloudConfigurationManager class, then all you need to do is add the nuget package “Microsoft.WindowsAzure.ConfigurationManager” to your project. And then, make sure you include the using statement “using Microsoft.Azure” in the class where you’re trying to access the cloud configuration file.

Hope this helps!!

[Update]

As pointed by Matthew Harris, this doesn’t seem to work for ASP.NET 5 json configs. While trying to read configuration specified in json file, please follow the approach mentioned in the below link.

http://stackoverflow.com/questions/30575689/how-do-we-use-cloudconfigurationmanager-with-asp-net-5-json-configs/30580006#30580006

Invoke a POST method with XML Request message in C#

Hi,

To invoke a POST method located at a particular URL with an XML request message, we need to follow the below steps:

  1. Create a request to the url
  2. Put required request headers
  3. Convert the request XML message to a stream (or bytes)
  4. Write the stream of bytes (our request xml) to the request stream
  5. Get the response and read the response as a string

This looks much easier when seen in code. 🙂 Keep reading…..

So, the code for the above steps looks something like this:

namespace HttpPostRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlMessage = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" +
            "construct your xml request message as required by that method along with parameters";
            string url = "http://XXXX.YYYY/ZZZZ/ABCD.aspx";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);


            byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(xmlMessage);
            request.Method = "POST";
            request.ContentType = "text/xml;charset=utf-8";
            request.ContentLength = requestInFormOfBytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestBytes, 0, requestInFormOfBytes.Length);
            requestStream.Close();


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
            string receivedResponse = respStream.ReadToEnd();

            Console.WriteLine(receivedResponse);
            respStream.Close();
            response.Close();
        }
    }
}

If the xmlMessage is formed correctly, then you should be getting the expected response from the web method located at the URL.

Hope this helps!

Restricting to only one running instance of an application in C#

Hi,

We all must have observed some time or the other that when you try to open an application that is already running, you get a pop up that says, “Another instance of the same application is already running” or something like that.

This post will show how you can implement that in your windows application using C#.

The main class used here is the Process class that is a part of System.Diagnostics namespace. Process class provides access to some local and also remote processes and can be used to start/stop these processes. Some static methods provided by Process class are GetCurrentProcess() and GetProcessesByName(string process_name).

These methods pretty much do exactly what they are named.

  • GetCurrentProcess() basically gets a Process component and links it to the current running process from which this method was called. That means that if we call this method from our app (which is what we’ll do shortly), the method returns a Process component that is linked to our app’s process.
  • GetProcessesByName(string process_name) returns an array of Process components that are currently running in the local system with the specified process name, process_name. So for example, if you have chrome browser running with multiple tabs open, then you can see in Task Manager that there are as many number of “Chrome.exe” processes running as there are tabs in your browser. Now if you call this method for “Chrome.exe”, you will get an array of Process components each having all the details of one chrome.exe process each.

NOTE : It is very important to note here that these methods simply GET the already existing and running instances of the processes. They DO NOT create new instances of Process class. Note the words “gets/returns” in the above bullet points.

So to implement this functionality, all you need to do is before you create a new instance of your application, get all the running processes and check the names of those processes with the currently running process. If you find such a process, it means that there is an instance already running and you should not create another instance for the same application. If not, just create a new instance for the application.

Check the below code. I have created a Windows Forms application with a very basic form with a label. In the Program.cs file, I have created a static method that performs the above mentioned check and returns either true or false based on whether it finds a process with the same name or not.

[STAThread]
 static void Main()
 {
     if (AnotherInstanceExists())
     {
           MessageBox.Show("You cannot run more than one instance of this application.", "Only one instance allowed to run", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
           
           return;
     }

     Form1 objMyForm = new Form1();
     objMyForm.ShowDialog();
 }
public static bool AnotherInstanceExists()
{
    Process currentRunningProcess = Process.GetCurrentProcess();
    Process[] listOfProcs = Process.GetProcessesByName(currentRunningProcess.ProcessName);
 
    foreach (Process proc in listOfProcs)
    {
       if ((proc.MainModule.FileName == currentRunningProcess.MainModule.FileName) && (proc.Id != currentRunningProcess.Id))
               return true;
    }
    return false;
 }

The method AnotherInstanceExists() initially makes a call to GetCurrentProcess() to get a Process component associated with the currently running process. Then it makes a call to GetProcessesByName() and passes the currently running process’s name as parameter. With the array of Process components that are returned from this method, it checks whether the current process ID and process module’s filename are the same. Basically it checks whether both these processes are same or not.

If the method returns true, the user is shown an error message that only one instance can be running for this application.

That’s all there is to do.

Hope this helps!

State Management using Cookies.

What are Cookies?

Cookies are nothing but a small piece of information that are stored at the client’s browser by the server. This small piece of information about the user is then sent by the browser in all subsequent requests to the same URL in the request. We can store anything in a cookie; General example of cookie usages are to store the user preferences, password remembering, storing user options, etc.

Generally cookies are stored a plain text files in the local disk of the user. Cookies can be accessed from anywhere in the application. Generally Cookies are lost after the user closes the browser but we can also have cookies that will persist even after browser is closed.

Cookies are mainly classified into two types:

  1. persistant
  2. non-persistant.

Persistant cookies:

As the name itself suggests, these cookies remain persistant in the client’s memory even after the browser is closed. They remain permanently in memory till they are explicitly removed or their expiration is reached.

Non-persistant cookies: These cookies do not remain in the client’s memory and are lost after browser is closed.

How to create cookies from code:

Generally we use the HttpCookie class to create an instance of a cookie for that session, then add the values that we want to be included in the cookie as key-value pairs. The below code explains this more clearly.

HttpCookie userCookie = new HttpCookie("infoCookie");
userCookie["username"] = "Amogh";
userCookie["City"] = "Hyderabad";
userCookie["Country"] = "India";

//adding the cookie to the Response object. This will be sent to the client on first request from the client.
Response.Cookies.Add(userCookie);

The example shown above is that of a NONpersistent cookie as it doesn’t specify any expiration time for the cookie. If we add an expiration to the cookie object, the cookie will become a persistent cookie. Example code is shown below.

HttpCookie userCookie = new HttpCookie("infoCookie"); 
userCookie["username"] = "Amogh";
userCookie["City"] = "Hyderabad";
userCookie["Country"] = "India";

//adding an expiration to the cookie
userCookie.Expires = DateTime.Now.AddDays(1);

//adding the cookie to the Response object. This will be sent to  the client on first request from the client.

Response.Cookies.Add(userCookie);

The “Expires” property of the HttpCookie object specifies that the cookie will expire after 1 day of its creation.

Reading values from cookie: Values from cookie can be read directly by using the Request object of the current HttpContext.

HttpCookie infoCookie = Request.Cookies["infoCookie"];
string city = infoCookie["City"];

Advantages of Cookies :

  1. Very easy to use.
  2. Browser takes care of sending and maintaining cookies from multiple sites

Disadvantages of cookies:

  1. Not secure as data is stored as plain text
  2. cookie size is limited to 4KB
  3. Some browsers may not support cookies. So care needs to be taken while using cookies in code.

Hope this helps!!

[Solution]configuration system failed to initialize – C# Exception

Hi,

Today I encountered an exception while working on an application. The exception was “configuration system failed to initialize”. The problem that I was having in my application configuration file was that I declared the <appSettings> tag immediately after the root tag <configuration>.

The schema of a configuration file mandates the “<configSections>” tag to be the first child of the root tag. Thus, if you put any other tag as the first child of root <configuration> tag, the application would throw an exception. So, ALWAYS, the <configSections> tag should immediately follow root <configuration> tag.

Correct Format:

<?xml version="1.0"?>
<configuration>
   <configSections>
      <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
          <section name="your_project_name.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </sectionGroup>

Wrong Format:

<?xml version="1.0"?>
<configuration>
   <appSettings>
       ...
       ...
       ...
   </appSettings>
   <configSections>
      .....
    </configSections>

This is just one of the reasons for which the exception is thrown. There are more than one reasons for it. For me, this solution worked out. Hope it works out to you as well! 🙂

Hope this helps!!

[QUESTION-Help required] Pagination in asp:DataGrid. Aligning page numbers to the center

Hi,

I’m using an asp:DataGrid control with Pagination. But I want the page numbers appearing at the bottom of the page to span all the columns of the DataGrid as opposed to the one that I’m currently getting. Please check below image. This is what I’m getting currently.

What I'm currently getting is this.
What I’m currently getting is this.

But I want the page numbers to span all the columns or at least appear a little spaciously (Not just under first column). Not just the first column as seen above. Any suggestions??

 

Thanks a lot!

[QUESTION- Please Help] IIS throwing HTTP 404 not found but requested resource actually exists. Requested URL also changing automatically.!

Hi all,

I’m facing a really weird scenario here with my local IIS. I have hosted multiple sites in the default website in my local IIS. One of them has the login page. From the login page, I’m redirecting the user to another page that is located in another site (which is also hosted in the same IIS inside default website virtual directory).

Now in the submit button click event of my login page, after authenticating the user, I have written a “Response.Redirect(redirect_url)“. the redirect_url is being formed dynamically and given as a parameter to the Redirect method.

While debugging, the final redirect_url that is being sent as parameter to Redirect method is:

http://localhost/CP/web/console/console.aspx?sk=3e3cc1a8-73c4-4945-b3f8-08af22ea4324.50008
But after I try to go to the next step, I’m suddenly getting a HTTP 404 error saying that the resource doesn’t exist and I have observed that Requested URL shown in the error page is different that what was dynamically sent to the Response.Redirect(…) method. See error page screen shot below.

localhost being appended automatically
localhost being appended automatically

In the error page, the requested url shows the value as

http://localhost/CP/web/console/localhost/CPLogin?err=5

whereas my actual requested url formed in the code is:

http://localhost/CP/web/console/console.aspx?sk=3e3cc1a8-73c4-4945-b3f8-08af22ea4324.50008

I’m just unable to understand why the requested url is getting changed automatically.! Also, I observe that “localhost” is being appended to the requested URL again which is not what is supposed to happen.

Thanks a lot.!

Getting a machine name of logged in user in asp.net

Hi,

I recently encountered this scenario and thought of blogging about it. To get the machine name of the logged in user, you can use the “GetHostEntry()” method provided in System.Net.Dns class.

GetHostEntry takes a string as parameter and it is the hostname or address of the machine whose entry we need to get. So in order to get the machine name, we need to make use of the server variable remote_addr.

GetHostEntry returns an IPHostEntry object and its HostName property would give the machine name of the logged in user. So the line of code would be

System.Net.Dns.GetHostEntry(Request.ServerVariables["REMOTE_ADDR"]).HostName;

 

Hope this helps!

How to implement a multi-column Dropdown list? See attached image for more clarity

Hi,

This post is more of a question than an article.

I want to implement a multi-column drop down box where in I should be able to filter the results appearing below as I type along with auto-complete feature. A sample implementation of what I want can be seen in the below image.

Multi-column-DropDown-Combo-Box

I want to implement a similar Drop down list using C#. Can someone please help me out with it? I have referred to THIS LINK which pretty much shows exactly what I’m expecting but it is being done in LightSwitch. I’m not really aware of LightSwitch but still I’m trying. Meanwhile, if someone can guide me in creating similar functionality in C#, ASP.NET, it would be great! 🙂

Thanks a lot!!

Converting HTML text to image using C#

Hi,

This post talks about converting HTML text to image. That is, saving as image, the html text as rendered in the browser!! (Unable to put it in proper words!! :@ )

The code uses an external dll (HtmlRenderer) that needs to be added in out project. HtmlRenderer namespace provides a class “HtmlRender” that provides an overloaded method “Render“. This method saves renders the html text and saves the outcome as an image.

The following code shows the usage of the method.

namespace HtmlToBmpImageDemo
{
     class Program
     {
         static void Main(string[] args)
         {
               Bitmap m_Bitmap = new Bitmap(400, 600);
               PointF point = new PointF(0, 0);
               SizeF maxSize = new System.Drawing.SizeF(500, 500);
               HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap), 
                                              "<html><body><p>This is a shitty html code</p>"
                                              + "<p>This is another html line</p></body>", 
                                               point, maxSize);
               
               m_Bitmap.Save(@"C:\Test.bmp");
         }
     }
}

The problem with this method is that if we include images in the HTML mark up text, the corresponding image doesn’t show the image in the created image (hope you understand the previous line!). There is yet another method of taking a screenshot of rendered html by opening a browser process in the background and then taking a screen shot of that. But I wanted a more lighter and simpler process and found this.

Hope this helps and please do let me know if there is any method of displaying images and then taking a screen shot of that rendered HTML.

Division by Zero doesn’t always raise an exception

In this post, I would like to point out that dividing a number by zero doesn’t always raise an exception as is generally taken for granted. The raising of exception depends upon the type of the number being divided by zero.

DivideByZeroException

As the name itself suggests, this exception is raised at run time when the compiler tries to divide a number by zero. But this exception is not raised at all times. For instance, take the code below:

int num1 = 150;
int num2 = 0;
int result = num1/num2; 

The above piece of code, when executed will raise the DivideByZeroException.

But this is not the case when we divide a number of type double with zero. For instance, if you execute the code below, it will not raise any exception and will just execute normally.

double num1 = 15.8
int num2 = 0 
double result = num1/num2;  

Now, this is not a bug but in fact, a very normal scenario. The result of this division will be “Infinity”, positive infinity, to be precise. the double type has a property for infinity. This infinity is just like any other number and can also be used in calculations. For instance, the following lines of code can be executed without any compilation errors or run time exceptions.

Console.WriteLine(15 + infinity);       //prints infinity
Console.WriteLine(15 - infinity);       //prints negative infinity
Console.WriteLine(infinity * 3);        //prints infinity again
Console.WriteLine(infinity * 0);        //prints NaN
Console.WriteLine(infinity / 1023);     //prints infinity
Console.WriteLine(1281 / infinity);     //prints zero
Console.WriteLine(infinity + infinity); //prints infinity
Console.WriteLine(infinity / infinity); //prints NaN
Console.WriteLine(infinity * infinity); //prints infinity

The double type provides methods to check if a number is infinity or not. Some of those properties are:

  1. double.IsInfinity(double num)
  2. double.IsPositiveInfinity(double num)
  3. double.IsNegativeInfinity(double num)

The type also provides properties like:

  1. double.PositiveInfinity
  2. double.NegativeInfinity
  3. double.NaN

This can be used in calculations where infinity is being used.

Please provide your valuable suggestions and comments to improve this tip.

Hope this helps!

Finding the Longest substring in a string that is a palindrome

Hi,

Recently my friend asked me this question so gave it a try and got it. So this is how the code goes:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SubStringPalindrome
{
class Program
{
static int maxLength;

static void Main(string[] args)
{
string inputString = “ootntannanitindennedadinidadeleveledaibohphobiatattarrattat”;
string currentStr = string.Empty;
List<string> listOfPalindromes = new List<string>();

char[] inputStrArr = inputString.ToCharArray();

for (int i = 0; i < inputStrArr.Length; i++)
{
for (int j = i+1; j < inputStrArr.Length; j++)
{
currentStr = inputString.Substring(i, j – i + 1);

if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(currentStr);
if (currentStr.Length > maxLength)
{
maxLength = currentStr.Length;
}
}
}
}

var longest =   from str in listOfPalindromes
where str.Length == maxLength
select str;

foreach (var item in longest)
{
Console.WriteLine(“Longest Palindrome : ” + item.ToString());
}
}

private static bool IsPalindrome(String str)
{
bool IsPalindrome = true;
if (str.Length > 0)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str.Substring(i, 1) != str.Substring(str.Length – (i + 1), 1))
{
IsPalindrome = false;
}
}
}
else
{
IsPalindrome = false;
}
return IsPalindrome;
}
}
}

Hope this helps!! 🙂

CodeProject

‘yield’ Keyword in C#

Hi,

This post is mainly about the ‘yield’ keyword provided in C#. I never really got a chance to use this keyword until now. So thought I would just blog about it. This blog is not of my own writing; I would say it is rather a re-blogging of a discussion about the keyword in this link.

yield‘ keyword is used in an Iterator block to provide a value to the enumerator object or to signal the end of an iteration. The syntax of yield statement is as follows:

yield return <expression>;
yield break;

The following example clearly illustrates the proper usage of the keyword. The example shows two ways of returning an IEnumerable of “Product” entities.

Version-1: Using yield return

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        foreach (Product product in products)
        {
            yield return product;
        }
    }
}

Version-2: returning the list

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList<Product>();
    }
}

The main usage of the yield keyword can be realized when we have to calculate the next value in the list or the next item in the list. In the second version above, when the return keyword is reached, the entire list is ready whereas in version-1, the entire list is not ready when the yield return statement is reached. Instead, for each occurrence of the yield return statement, the next item in the to-be-returned list is calculated.

One really good use of this type of functionality is that this helps spread the computational cost over a larger time frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

In the above two versions, the one that is preferable is the version-2 as the product list is finite. So we can just calculate the complete list before itself.

And above all, thanks to the author of that post that  helped me clearly understand the usage of the keyword.

Hope this helps!! 🙂