Posts

Creating csv file by reading text file by placing columns and data separately

The below code will read the text file and create csv file with columns and data. let us say access.txt file have data as like below Name:,4th Floor, IT Clearance name:,iT Card number:,1234 Name:,Graham, John Personnel Clearance Pair Clearance name:,Temps Card number:,23489 : : etc so, use below code to read the text file and create csv file try  { StreamReader sr = new StreamReader("C:\\Access.txt"); string csv = string.Empty; string csv1 = string.Empty line = sr.ReadLine(); line = line .split(":,"); if(line.length>1){ csv += line[0] + ','; // Adding header columns into string csv1 += line[1]; // Adding the values against each header } while (line != null) //Continue to read until you reach end of file { line = sr.ReadLine(); } csv += "\r\n"; //Add new line. csv + = csv + csv1 + "\r\n"; //close the file sr.Close(); Console.ReadLine(); //Download the CSV file. Response.Clear(); Response.Buffer = true; Response.AddHeader(...

Splitting string in SQL Server

For sql server 2016 before, Try to create user defined function like below and use it CREATE FUNCTION [dbo].[SplitString] (  @Input NVARCHAR(MAX), @Character CHAR(1) ) RETURNS @Output TABLE ( Item NVARCHAR(1000) ) AS BEGIN DECLARE @StartIndex INT, @EndIndex INT SET @StartIndex = 1 IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character BEGIN SET @Input = @Input + @Character END WHILE CHARINDEX(@Character, @Input) > 0 BEGIN SET @EndIndex = CHARINDEX(@Character, @Input) INSERT INTO @Output(Item) SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1) SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input)) END RETURN END SELECT * FROM [SplitString]('John,Jeremy,Jack',',') You can use the below statement for split the string in sql. It is available in 2016 onwards SELECT * FROM STRING_SPLIT(' John,Jeremy,Jack ',',')

Clearing browser cache using script

Please keep below script code in clearcache.js file (function () { var process_scripts = false; var rep = /.*\?.*/, links = document.getElementsByTagName('link'), scripts = document.getElementsByTagName('script'); var value = document.getElementsByName('clear-browser-cache'); for (var i = 0; i < value.length; i++) { var val = value[i], outerHTML = val.outerHTML; var check = /.*value="true".*/; if (check.test(outerHTML)) { process_scripts = true; } } for (var i = 0; i < links.length; i++) { var link = links[i], href = link.href; if (rep.test(href)) { link.href = href + '&' + Date.now(); } else { link.href = href + '?' + Date.now(); } } if (process_scripts) { for (var i = 0; i < scripts.length; i++) { var script = scripts[i], src = script.src; if (src !== "") { if (rep.test(src)) { script.src = src + '&' + Date.now(); } else { script.src = src + '?' + Date.now(); } } } } })(); And add below scri...

System.InsufficientMemoryException: Insufficient winsock resources available to complete when working with WCF

Some times when calling API's or web services we will get memory leakage exceptions in .Net like blow EXCEPTION: System.InsufficientMemoryException: Insufficient winsock resources available to complete socket connection initiation. ---> System.Net.Sockets.SocketException: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full 10.7.162.159:808 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Connect(EndPoint remoteEP) at System.ServiceModel.Channels.SocketConnectionInitiator.Connect(Uri uri, TimeSpan timeout) So, it seems s ome where in the api's or web service or wcf program logic, network related objects used and those are not disposed hence causing the above mentioned exception. What exactly happening when you use network streams open is, your computer might have limited connections and you are creating and not disposi...

How to figure out .net ide exception that, when Open visual Studio 2015 throwing error System.Exception of type 'system.Exception' was thrown. At Microsoft.Visual studio.shell.interop.IVshell5.LoadpackagewithContext?

The problem due to failed installation of some packages. You can try to remove the existing VS 2015 as below and reinstall. Go to Control Panel—Programs and Features, if there has 'Microsoft Visual Studio 2015', right click it and choose 'Uninstall' Try to delete the following installed folders: (you can back up those folders before any modification, in case we need to roll back) Go to the folder: %ProgramData%\Microsoft\VisualStudio and delete the 'Packages' folder and 'Setup' folder if there has. Go to the Visual Studio installation folder (normally under %ProgramFiles(x86)%\Microsoft Visual Studio) and delete the folder '2015'

Splitting String in SQL Server

SQL SERVER 2016 SELECT * FROM STRING_SPLIT('John,Jeremy,Jack',',') STRING_SPLIT is built - in - function sql server 2016 and you can directly use it. I f SQL SERVER is Below 2016 then Write user defined function which returns tabular value like below CREATE FUNCTION [dbo].[SplitString] (           @strString NVARCHAR(MAX),       @splitCharacter CHAR(1) ) RETURNS @Output TABLE (       Item NVARCHAR(1000) ) AS BEGIN       DECLARE @StartIndex INT, @EndIndex INT       SET @StartIndex = 1       IF SUBSTRING(strString , LEN(strString ) - 1, LEN(@strString)) <> @splitCharacter        BEGIN             SET @strString = @strString + @splitCharacter        END       WHILE CHARINDEX(@splitCharacter  @strString) > 0       BEGIN...

How to resolve microsoft visual studio 2010 IDE error that microsoft visual studio has encountered a problem that need to close debug or restart when opening project?

try to close all of your .Net IDE's which got opened and reset IDE dev environment. Access the visual studio command prompt with below path. Start->Program files->Microsoft Visual Studio 2010-> Tools->Visual studio Command prompt.. Just open it and type below command and execute Devenv /ResetSkipPkgs so the above command will reset IDE and now open your application and rebuild all solutions.

Clearing browser cache of script files programmatically

Please add below script into a file called clearcache.js (function () {    var process_scripts = false;     var rep = /.*\?.*/,     links = document.getElementsByTagName('link'),     scripts = document.getElementsByTagName('script');     var value = document.getElementsByName('clear-browser-cache');     for (var i = 0; i < value.length; i++) {         var val = value[i],             outerHTML = val.outerHTML;         var check = /.*value="true".*/;         if (check.test(outerHTML)) {             process_scripts = true;         }     }     for (var i = 0; i < links.length; i++) {         var link = links[i],         href = link.href;         if (rep.test(href)) {       ...

Customized path change for MVC Views

When we create MVC project all the Models, View and Controllers will be created with separate folder structure. after publishing the MVC you will get folder structure as  BIN Views Images Fonts Styles Scripts Global.asax Packages.config web.config so, we will place all the folders and files into a folder called WebSite1 and map that folder to IIS virtual directory and use it. But if we want to keep another sub folder within the WebSite1 then we have to make changes to the default  return view(). Required folder structure WebSite1 WebUIFileUpload                   BIN Views Images Fonts Styles Scripts Global.asax Packages.config web.config   we can change the default paths using below process public class CustomViewEngine : WebFormViewEngine {     public CustomViewEngine()     {         var viewLocations =  new[] {   ...

MVC Project publish Steps

Generally after we create asp.net project we used to deploy the site at IIS by creating virtual directory my mapping physical path code. But MVC project  has different process to publish at IIS we have to follow below steps to create deploy folder MVC Project Publish Steps 1 . Select Project at Solution Explorer and right click on it 2 . Select Publish 3 . Select Profile and Click Next button 4 . Specify the Profile Name as it is temporary to create 5 . Click on Next button 6 . Select the Publish Method from the drop down as "Web Deploy Package" and Click Next button 7 . Specify the Package Location path so that it will place the package in zip 8 . Click on Next button 9 . Specify Site name if you want otherwise leave it as it is not mandatory field and then Click Next button 10. Select the configuration as Release from the drop down 11. Click on Next button 12. See the preview 13. Click On Publish It will publish the entire project and place the deployme...

Exception handling in ASP.NET MVC

Exception handling is the process of handle the occurrence of exceptional conditions requiring special processing and displaying the customized messages or logs. Exception handling is important in any application. In ASP.NET we can handle exceptions in the following two ways: Try-catch-finally block at method level Using Application_Error In ASP.NET MVC we have a larger list of ways to handle exception such as: Simple way Override “OnException” method Using “HandleError” Attribute Inheriting from “HandleErrorAttribute” Handling HTTP errors Global Error handling in MVC Simple way The simplest wayis to use the traditional .NET exception handling style i.e. try and catch block. Now when exception happens catch block gets executed and it redirects to the error view. But if we use this method then we will not be utilizing MVC exception mechanism properly and completely. In the further sections we will discuss five important ways by which we can utilize MVC provided ...

New ASP.NET Session_Id creation

When you want it to change session id when someone logs in to website just before you set  initial session variables. try to use below code snippet  SessionState.SessionIDManager Manager = new SessionState.SessionIDManager();  string NewID = Manager.CreateSessionID(Context);  string OldID = Context.Session.SessionID

URL query string length limitations

HTTP states there is no limit to the length of a query string, but it indicates the host name is limited to 255 characters because of DNS limitations. While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software.  Internet Explorer (Browser) Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer. Edge (Browser) The limit appears to be around 81578 characters.  Chrome It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that. Firefox  After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters. Safari At least 80,...

Read file content using javascript

We can upload the file using file control and read content of that file using below script code. <html> <head>     <script>       var openFile = function(event) {         var input = event.target;         var reader = new FileReader();         reader.onload = function(){           var text = reader.result;           var node = document.getElementById('codeInTest');           node.value = text;         };         reader.readAsText(input.files[0]);       };     </script> </head> <body>     <input type='file' accept='text/plain' onchange='openFile(event)'><br>     <textarea rows="17" cols="129" wrap="virtual" id="fileContent"></textarea> </body...

ASP.NET Session_Id Cookie in ASP.NET

“ASP.NET_SessionId” cookie in ASP.NET When a user opens his web browser and makes a request to a ASP.NET Web Application for which a cookie based Session is enabled, Server generates a new Session Id and sends it to web Browser as a cookie with the name "ASP.NET_SessionId". Applications in the same DNS domain share the same Session Id and cookie. When the user browses within the same DNS domain, the browser sends same Session Id and cookie to the domain. Since it is shared across applications in a domain, so ASP.NET doesn't remove the cookie when the session is expired or Session.Abandon() is invoked. Because of this design, the code that is used to check if a Server Session is actually expired doesn't work properly. Generally we use following code snippet to check if session is expired. if (Session.IsNewSession) {     if (Request.Headers( "Cookie" ) != null && Request.Headers( "Cookie" ).IndexOf( "ASP.NET_SessionId...