Wednesday, April 19, 2023

How to render a Razor view to string in ASP.net MVC

 Sometimes we need to get the Razor view to a string, in order to use it for various purposes. I had a requirement where I needed to generate a PDF file from the Razor view.

I used below method to convert the Razor view to a string and used this string to generate a PDF file.

Below is the detailed explanation of that:

Steps:

1. Get the viewResult using the view name.

2. Get the viewContext using the view.

3. Render the data to the StringWriter class object using the viewResult and viewContext.

4. Finally release the view and get the string from StringWriter class object.

public string RenderRazorViewToString(this Controller controllerName, string viewName, object model)

        {

            controller.ViewData.Model = model;

            //used a StringWriter to get the Razor contents into it.

            using (var sw = new StringWriter())

            {

                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);

                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);

                viewResult.View.Render(viewContext, sw);

                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);

                return sw.GetStringBuilder().ToString();

            }

        }


This worked like a charm for me. Now you can use this return string for your custom needs.

Hope this helps somebody out there.



Thursday, July 3, 2014

The type initializer '' threw an exception.

Mainly this error occurs when it fails to load a dependent dll/assembly. It couldn't find the dependency, or the version number was different.

This error mostly occurs when you deploy your application to production server. It might work fine in development machine. Things to make sure in this case:

All your dependencies are deployed properly.
Check the version numbers for the dependencies.

I had this issue when my multiple projects where using a logging dll. It worked fine in dev machine, but when deployed to the test server, booommmm..... ended up with this error.

So I made sure that all the projects in my solution are referring to the logging dll from same common location (may be a folder in the solution/GAC to hold common shared assemblies), with same version number. After making these changes and making sure all other dll's are deployed correctly, it worked like a charm.

Hope this tip helps somebody...... njoy..

Wednesday, June 18, 2014

The Specified Store provider cannot be found in the configuration or is not valid - entity framework

Check your machine.config to see if any providers mentioned in the <DbProviderFactories> section. If not, add the required provider to this section.

This solved mine.

Thursday, March 13, 2014

How to install a windows service in a server which doesn't have Visual Studio installed

If you have visual studio installed in a server, it would be easier to install a windows service, by using installutil.exe. However this have to be done from Visual Studio command prompt.

But how can you install if you don't have Visual studio command prompt in the server.

Below is the solution:

SC Create <Service name> binPath= "complete path of the exe file" DisplayName= "MyService"

ex:-  sc create MyService binPath= "C:\temp\Service1.exe" DisplayName= "MyTestService"

The service will be created and will be displayed in services.msc as MyTestService. If you right click and check the properties of the service, it will show the service name as MyService.

IMPORTANT:- Make sure you add a space after the "=" for the arguments.
Like binPath= "C:\temp\Service1.exe" DisplayName= "MyTestService". You can see the space marked in purple color. This has to be there to run the command successfully.

Otherwise, it doesn't even throw error and you will not have a clue of what is happening.

You can use SC Delete command to delete the service from the console.

Friday, February 21, 2014

IIS Error & Solutions - Tips

Got Error: "http error 500.19 <modules runAllManagedModulesForAllRequests="true" />"

Soultion: Deleting this line from web.config solved it.

Got Error: "HTTP Error 404.3 - Not Found  The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map."

Solution: Ran the command "aspnet_regiis.exe -ir" from Visual studio command prompt. This .exe can be found in
%windir%\Microsoft.NET\Framework64\v4.0.30319


Got Error while hosting WCF Web service in IIS:
"the configuration section 'protocolmapping' cannot be read because it is missing a section declaration"

Solution: Please make sure the application pool that is used for the website need to be setup to use .Net 4.0 framework.


More tips on the way...

Thursday, December 19, 2013

Extracting values from an XML string using SQL query in oracle database

There are two methods you can use for extracting values from XML string (a column in a table). The column type will be XMLType.

These methods are EXTRACT(columnName, xpath). This returns list of nodes, also a record if extracting with a unique filter value.
You can also use ExtractValue(columnName, xpath) - This will work only for a single node, not for a collection of nodes. This way you can retrieve value from a unique record.


See examples below:

<Person>
    <Name>Test</Name>
    <Address>
        <Street Number=1345>Monroe St</Street>
        <City>TestCity</City>
        <Zip>12345</Zip>
    </Address>
</Person>

Assume this xml data in column
You can extract the street number attribute value using the query as below:

This can return multiple records:
select extract(columnName,'/Person/Address/Street/@Number') as StreetNumber from Table1;

For returning single record:
select extract(columnName,'/Person/Address/Street/@Number') as StreetNumber from Table1 where ID = 200;

Also For returning single record only:
select extractvalue(columnName, '/Person/Address/Street/@Number') as StreetNumber from Table1 where ID = 200;

I have used this and works like a charm.
Hope this finds useful to you also.
Njoyy...

Wednesday, August 7, 2013

‘MyEntities’: type used in a using statement must be implicitly convertible to ‘System.IDisposable’

‘MyEntities’: type used in a using statement must be implicitly convertible to ‘System.IDisposable’

When trying to access the entity object which is in a different project, I added the reference of the project having the entity object to the new project and was trying to use the code block as below:

 using (Entities entities = new Entities(entityConnStr))
{

}

This gave me the error. The solution for this was to add a reference to 'System.Data.Entity' in the new project. After this it started working for me.