Tech NovoGeek

...Technology Simplified

Monday, November 17, 2014

Accessing a variable using a string containing the variable's name

No comments :
 public class MsgCodes
    {
       public string GetString(string errorCode)
       {
           return (string)this.GetType().GetField(errCode).GetValue(this);
       }
       public const string strError= "No error -just display this text";

Tuesday, November 4, 2014

Error creating new MVC project

No comments :

I have had a problem with VS2010 where when I tried to create a new MVC 4 Web Project I would get errors thrown where it could not successfully add references to the project.

    Failed to initialize Powershell host, for the entity framework and Jquery. The error: The following packages failed to install from ‘C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Packages’

    EntityFramework.5.0.0: Failed to initialize the Powershell host. If your powershell execution policy setting is set to AllSigned, open the package manager console to initialize the host first.

    jQuery.1.7.1.1: Failed to initialize the Powershell host. If your powershell execution policy setting is set to AllSigned, open the package manager console to initialize the host first.

To resolve the error,
Make sure Powershell 2.0 is installed on your machine
You can get the Windows Prowshell 2.0 from here:
http://www.microsoft.com/en-in/download/details.aspx?id=9864

If thIS does not resolve the issue try t o launch the PowerShell console with local Administrator rights and run the following command.

Set-ExecutionPolicy AllSigned

Make sure you restart Visual Studio!

Tuesday, October 21, 2014

Cheat sheet for Bootstrap 3.0

No comments :
Best way of learning new technology is learning the skill and keeping the key points noted and make a cheat sheet of just maximum of 4 pages would give you clear idea of new languages , syntaxes and samples.
You could also easily remember all the key points and also gives concise set of notes used for quick reference

Recently I started learning new framework Bootstrap 3.0, which has huge set of classes and different ways to use them.
Here is the cheat sheet for Bootstrap 3.0 for download

Friday, December 20, 2013

MaintainScrollPositionOnPostback not working in Firefox and Chrome browsers

No comments :
You just need to put the script below in your page where you want to maintain scroll position or in your master page. And I have tested this script in 5 major browser and luckily it works in all.

Wednesday, October 9, 2013

Asp.net - The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

No comments :
Asp.net - The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

I have this issue when I want to change button text in Page_init method.
This occured because I am using resource file to bind Button text.

Example:

<button class="simpleFormButton" id="btnSaveFinishButton" runat="server" type="button">
                   &lt;%=GetLocalResourceObject("SaveandFinish")%&gt;</button>

Replacing '<%=' to '<%#' solved my issue.
Hope this helps you as well.

Tuesday, August 27, 2013

Find nth Min/Max values in SQL Server

No comments :
Finding Nth minimum salary:

1.In SQL Server 2000/2005

SELECT salary FROM employees e1 WHERE (N = (SELECT COUNT(DISTINCT (e2.salary))
FROM employees e2 WHERE e2.salary <= e1.salary))

Finding Nth maximum salary:

1.In SQL Server 2000/2005

SELECT salary FROM employees e1 WHERE (N = (SELECT COUNT(DISTINCT (e2.salary))
FROM employees e2 WHERE e2.salary >= e1.salary))

Hope you find it useful.

Wednesday, August 7, 2013

Where is the list of pinned start menu and taskbar items stored in Windows 7

No comments :
You can find pinned apps in:
%AppData%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar
and for the start menu apps go to:
%AppData%\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu

Thursday, November 15, 2012

Programming in HTML5 with JavaScript and CSS3 Specialist

No comments :

Today i took my second Certification and it is on Exam 70-480: Programming in HTML5 with JavaScript and CSS3.
I got certified with score 800/1000

Experts-Exchange update

No comments :

Overall Wizard certified with 301,676 Expert points. Individually Master certified in

  • C# Programming Language
  • Programming for ASP.NET
  • .NET

Tuesday, October 16, 2012

Removing bom ‘  ‘ from file c#

No comments :
UTF8Encoding utf8WithoutBom =  new UTF8Encoding(false); 
using (TextWriter writer = new StreamWriter(outputpath,false,utf8WithoutBom))
{
newDoc.Save(writer);
}

Thursday, October 11, 2012

How to display current Date and Time calling Templates in XSLT using C#

No comments :
The below script converts 'dd-mm-yyyy' to 'yyyymmdd' format.
<xsl:template name="formatDate">
<xsl:param name="dateTime" />
<xsl:variable name="dd" select="substring($dateTime,1,2)" />
<xsl:variable name="mm" select="substring($dateTime,4,2)" />
<xsl:variable name="yyyy" select="substring($dateTime,7,4)" />
<xsl:value-of select="concat($yyyy,$mm,$dd)" />
</xsl:template>


<xsl:call-template name="formatDate">
<xsl:with-param name="dateTime" select="TestDate" />
</xsl:call-template>

Tuesday, September 4, 2012

Extract characters from string in SQL Server

No comments :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[udf_GetAlphabets]
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^A-Z]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^A-Z]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END


--SELECT dbo.udf_GetAlphabets('ABC1234DEFGH789')


Instead if you want to retrieve only numeric values from string replace the pattern '%[^A-Z]%' with '%[^0-9]%'

Thursday, July 26, 2012

It is not possible to run two different versions of ASP.NET in the same IIS process

No comments :

Server Application Unavailable

The web application you are attempting to access on this web server is currently unavailable.  Please hit the "Refresh" button in your web browser to retry your request.

Administrator Note: An error message detailing the cause of this specific request failure can be found in the application event log of the web server. Please review this log entry to discover what caused this error to occur.

You will also receive Event ID 1062 in Event Viewer that says:

"It is not possible to run two different versions of ASP.NET in the same IIS process. Please use the IIS Administration Tool to reconfigure your server to run the application in a separate process."

image

The simple solution for this is:

Create a new application pool and move the site that you will be upgrading to that pool. Once you have placed the site or virtual directory in new application pool, then upgrade to the new framework version.

Follow the below steps to create resolve this issue:

image

 

image

U1ntitled

Wednesday, July 11, 2012

Windows Service -- creation , Installation , Uninstallation

No comments :

In this post we will have a look at how to create windows service in c# and how to install or uninstall and how to start service in detail.
First let us know what a window service is and uses of windows service and then we will see how to create windows service.

What is Windows Service?

Windows Services are applications that run in the background and perform various tasks. The application that does not need any user interface. Windows Services are started automatically when computer is booted. Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.

How to Create a Windows Service

Open visual studio (I’m using Visual studio 2010) --> Select File --> New -->Project--> select Windows Service from c#

clip_image002

click ok button to create our project that should like this

clip_image004

In Solution explorer rename Service1.cs file to SampleService.cs.

And then right click on the page to select Properties then change ServiceName to SampleService.

clip_image005

Open SampleService.cs in design view and right click on it to Add Installer files to our application. The main purpose of using Windows Installer is an installation and configuration service provided with Windows. The installer service enables customers to provide better corporate deployment and provides a standard format for component management.

clip_image006

You can now see two controls: ServiceProcessInstaller1 and ServiceInstaller1

Now right click on serviceProcessInstaller1 and select properties in that change Account toLocalSystem

clip_image007

Now right click on ServiceInstaller1 and change properties

StartType to Automatic

DisplayName to ‘SampleService’

After completion of setting all the properties now we need to write the code to run the windows services.
We implement windows service to write entry every minute into a file.
If you observe our project structure that contains Program.cs file that file contains Main() method otherwise write the Main() method like this in Program.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace WindowsService1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SampleService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
Open SampleService.cs file and add namespaces for writing to file and timerin codebehind of SampleService.cs file

using System.IO;
using System.Timers;
  public partial class SampleService : ServiceBase
{
Timer timer = new Timer();

public SampleService()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
TraceService("start service");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
}

protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService("Another entry at " + DateTime.Now);
}

private void TraceService(string content)
{
FileStream fs = new FileStream(@"C:\SampleService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
}
In OnStart method the event ElapsedEventHandler is used to run the windows service for every one minute
Then build the application and install the service.
To install windows service in your follow these steps
Start --> All Programs --> Microsoft Visual Studio 2010 --> Visual Studio Tools --> Open Visual Studio Command Prompt
After open command prompt point to your windowsservice1.exe file in your project

clip_image009
Installutil windowsservice1.exe (Give your windows service exe file name) and now press enter button.

clip_image011

After successful installation of service, to view it:
Start --> Control Panel --> Open Control Panel --> Select Administrative Tools --> Computer Management --> Services and Applications --> Services --> Open services

clip_image013
Right click on sampleservice and start the service.
Note: If we want to uninstall the installed windows service go to VS 2010 command prompt and point to your service same as for installation and type statement installutil /u windowsservicesample.exe
Once the service is started, and you will be able to see entries in the log file we defined in the code.

Now open the log file in your folder that Output of the file like this

image

XSLT transformation using Windows Service

No comments :

private string ArchivePath = @"c:\Archive\";
private string InputPath = @"c:\InputFiles\";
private string OutputPath = @"c:\OutputFiles\";
To write the exception entries to Event Viewer

protected override void OnStart(string[] args)
{
Transformation();
try
{
// Uncomment this line to debug...
//System.Diagnostics.Debugger.Break();

_thread = new System.Threading.Thread(Transformation);
_thread.Start();
EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);
}
catch (Exception ex)
{
// Log the exception.
EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
}


private void Transformation()
{
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
// Source paths
string xsltFilePath = "D:\\Transformation.xslt";
// refer link http://technovogeek.blogspot.ie/2012/07/how-to-display-current-date-and-time-in.html for using sample XSLT
// Compile the style sheet.
XsltSettings xslt_settings = new XsltSettings();
xslt_settings.EnableScript = true;
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xsltFilePath, xslt_settings, new XmlUrlResolver());
try
{
string[] inputfileEntries = Directory.GetFiles(InputPath);
foreach (string fileName in inputfileEntries)
{
// Load the XML source file.
XPathDocument doc = new XPathDocument(fileName);

// Create an XmlWriter.
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;

if (!System.IO.Directory.Exists(OutputPath))
System.IO.Directory.CreateDirectory(OutputPath);
string file = System.IO.Path.Combine(OutputPath, System.IO.Path.GetFileNameWithoutExtension(fileName) + "_OUTPUT.xml");

XmlWriter writer = XmlWriter.Create(file, settings);

if (!System.IO.Directory.Exists(ArchivePath))
System.IO.Directory.CreateDirectory(ArchivePath);
string destFile = System.IO.Path.Combine(ArchivePath, System.IO.Path.GetFileName(fileName));
System.IO.File.Copy(fileName, destFile, true);
// Execute the transformation.
xslt.Transform(doc, writer);
writer.Close();
System.IO.File.Delete(fileName);
}
}
catch (Exception ex)
{
string str = "Unable to process the Conversion ";
}
}