Get password for IIS Application Pool account

Hi,

There are many instances where you have to provide a custom account identity to an App pool in IIS. There are also instances where you might have forgotten the password for that account which has to be set as identity for that Application Pool. In such cases, you can use the APPCMD command to retrieve the password for that user. One thing to remember is that there has to be an app pool existing in the machine already which has been assigned that account’s Identity for us to retrieve it’s password. Please note: This can be used for IIS 7 and above.

APPCMD:

appcmd is an IIS tool used to manage IIS server. It provides many functions that can be used to manager server related activities like create/configure sites, start/recycle/stop app pools, etc.

Retrieve Password of an App Pool identity account:

  1. To retrieve password for an app pool identity account, open the command prompt in administrative mode.
  2. Navigate to C:\Windows\System32\inetsrv directory. This is the location where appcmd.exe exists.
  3. Type the below command and press enter.
    appcmd.exe list apppool <<app_pool_name>> /text:*
    For example: I have an app pool in my IIS named SampleAppPool which has been assigned a particular account’s identity whose password I would like to retrieve. So I would enter the below command in command prompt.

    cmdPress enter and the result will be as shown below. Due to security reasons, I have removed the username and password from the image but trust me, it shows the username and password there.resultHope this helps!

Consuming SOAP web services from iOS (Objective-C)

Hi,

In this post, I’ll show you how to consume a SOAP web service (asmx web service) from iOS. It’s pretty easy to start off with.

There are many links that talk about the use of many frameworks like ASIHttp framework, JSON Framework, wsdl2objc tool, etc. But for the purpose of this post, I would like to keep it simple (KISS! ;-)) Those frameworks are basically used for consuming web service methods that are more complex and those that return JSON response or things like that.

More on those later. For now, let’s concentrate on consuming a very basic ASMX web service hosted by w3schools.org, Temperature conversion web service.

As you can see, this web service exposes two methods: Convert a given temperature from Celsius to Fahrenheit and vice versa. In this post, let’s consume the first one (Celsius to Fahrenheit method).

The steps to follow for consuming the service from XCODE are given below:

  1. Create the request SOAP Envelope message as string
  2. Create a request to the URL
  3. Add required request header elements
  4. Initiate the request
  5. Implement connection delegate methods
  6. Parse the response.

For creating the soap request envelope message, open the method definition in the browser and copy-paste the request string as shown in the page. A sample is shown below:

soap Message

Note the format specifier in the middle of the soap message. That is to take the value entered by the user from the text field.

Celsius

Next step is to create a request to the URL of the web service. Sample code is shown below:

Request

Next, add the required header elements to the request object. You can find out what header elements are required in the message by looking at the sample request objects shown in the webpage of the service’s method. Sample code shown below:

Headers

Finally, set the body of the request by converting the soapMessage to bytes (shown in the last step above).

Next step is to implement the NSURLConnection delegate methods in the application. These methods are used to implement functionality at different stages of the request. A sample of the methods is shown below:

Connection Methods

The code of the connection methods is given below:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.webResponseData  setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.webResponseData  appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Some error in your Connection. Please try again.");
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Received %d Bytes", [webResponseData length]);
    NSString *theXML = [[NSString alloc] initWithBytes:
                        [webResponseData mutableBytes] length:[webResponseData length] encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",theXML);
    
    //now parsing the xml
    
    NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myData];
    
    //setting delegate of XML parser to self
    xmlParser.delegate = self;
    
    // Run the parser
    @try{
        BOOL parsingResult = [xmlParser parse];
        NSLog(@"parsing result = %hhd",parsingResult);
    }
    @catch (NSException* exception)
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Server Error" message:[exception reason] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return;
    }
}

In the last method, you can see that we have written some code to parse the response received from the web service.
Now, to enable our application to parse the response XML, we need to indicate that our app implements the NSXmlParserDelegate interface.

For this purpose, specify the same in the interface file as shown below:

interface

Now, the next step is to implement the NSXmlParserDelegate methods. It has 3 methods:

  1. didStartElement
  2. foundCharacters
  3. didEndElement

The code of the above methods is given below:


//Implement the NSXmlParserDelegate methods
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:
(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    currentElement = elementName;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([currentElement isEqualToString:@"CelsiusToFahrenheitResult"]) {
        self.resultLabel.text = string;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"Parsed Element : %@", currentElement);
}


The foundCharacters method is called when an XML tag is encountered that has some characters between the start and end tag. In our case, the response is wrapped between the CelsiusToFahrenheitResult tag. The characters that are found between the start and end tag are stored in the NSString variable string. Hence the code. The result string found is assigned to the result label on the screen.

When you put all the required pieces of the code together and run the app, you get this result.

result

When the user enters the celsius value in the text box and presses the button, the web service is called and the resultant xml response is parsed and the resulting value is displayed on to the screen.

I have attached the complete sample application source code here. Do have a look. You can download a zip copy of the same there from the bottom right of the page.

Hope this helps!

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!

[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!!

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!!

Error Condition: HttpException: maxRequestLength exceeded. ASP.NET

Hi,

While building ASP.NET web applications, we all would have almost certainly used the file upload control. But sometimes, we might encounter an exception message which reads, “System.Web.HttpException: maxRequestLength exceeded”.

The cause of this exception is simple. “maxRequestLength” attribute of the “httpRuntime” tag specifies the maximum size of input files that can be uploaded. By default, the value of this attribute in ASP.NET 4.0 is 4096KB (4 MB).

This value is set in the “machine.config” file which sets the maximum allowable file size for the entire machine as 4MB. This can be easily changed by modifying the “machine.config”. The configuration entry is as follows:

<httpRuntime maxRequestLength=”4096″ />

The size is always mentioned in “Kilo Bytes”. If we want the maximum allowable size of files to be say 25MB, then all we need to do is change the value of “maxRequestLength” attribute to 25600.

<httpRuntime maxRequestLength=”25600″ />

The above line would allow files up to 25MB to be uploaded. If this entry is added in the machine.config file, then all websites in that machine would allow files up to 25MB to be uploaded. If that entry is added in a particular website’s “web.config” file, then only that website would allow files up to 25MB to be uploaded. Other websites would allow only up to 4MB (Default size) files to be uploaded.

Just as an addition, the “machine.config” file is located at “%SystemRoot%\Microsoft.NET\Framework\Version\Config\machine.config”.

“SystemRoot” is the location where Windows is installed. Generally it is “C:\Windows”.

Hope this helps … 🙂