Absolute Thoughts....

  Home  |   Contact  |   Syndication    |   Login
  9 Posts | 0 Stories | 12 Comments | 0 Trackbacks

News

Archives

Image Galleries

Friday, November 6, 2015 #

This was a common error which we get when we are using LocalDB for a website running under IIS. Everything will work fine if we run the website under IIS Express i.e. when we run through Visual Studio. Once we deploy the site into actual IIS we get an error as shown below.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start. )

This error message will not give a clear idea but we will get additional information in Windows Event log. Looking in the Application section under Windows Logs we find the following message:

Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.

This message clearly says, the problem we're facing is that the user profile needs to be loaded.

To fix this we need to edit applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Enabling loadUserProfile is not enough to fully load user profile, we also need to enable setProfileEnvironment, i.e. set to true.

<applicationPools>
    <add name="DefaultAppPool" />
    <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
    <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
    <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
    <add name=".NET v4.5 Classic" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
    <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
    <applicationPoolDefaults managedRuntimeVersion="v4.0">
        <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
    </applicationPoolDefaults>
</applicationPools>

Happy coding…!!! Winking smile


Friday, May 2, 2014 #

Lets take a sample XML file and name it as Meeting.xml.

<?xml version="1.0" encoding="utf-8"?>
<billing>
  <item>
    <id>1</id>
    <customer>Pavan Kumar Pabothu</customer>
    <type>Personal Meeting</type>
    <date>4/5/2012</date>
    <hours>1</hours>
    <contact>
      <phone>
        <no>279102</no>
        <type>home</type>
      </phone>
      <phone>
        <no>9999995929</no>
        <type>mobile</type>
      </phone>
    </contact>
  </item>
  <item>
    <id>2</id>
    <customer>Reddaiah Raju</customer>
    <type>Official Meeting</type>
    <date>3/20/2014</date>
    <hours>4</hours>
    <contact>
      <phone>
        <no>2375226</no>
        <type>home</type>
      </phone>
      <phone>
        <no>998884888</no>
        <type>mobile</type>
      </phone>
    </contact>
  </item>
  <item>
    <id>3</id>
    <customer>Kishan Chand Yadav</customer>
    <type>Party</type>
    <date>4/20/2014</date>
    <hours>1</hours>
    <contact>
      <phone>
        <no>9988776652</no>
        <type>home</type>
      </phone>
      <phone>
        <no>9988776654</no>
        <type>mobile</type>
      </phone>
    </contact>
  </item>
</billing>

We can read the XML using below code.

<html>
<head>
  <title></title>
    <script src="Scripts/lib/jquery-1.7.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            $("#dvContent").append("<ul></ul>");
            var customerInfo = [];                    

            $.get("Data/Meeting.xml", function (xml) {
                $('item', xml).each(function () {
                    // Converting a XML to JSON object.
                    var loc = {
                        "ID": $(this).find("id").text(),
                        "Name": $(this).find("customer").text(),
                        "Type": $(this).find("type").first().text(),
                        "Date": $(this).find("date").text(),
                        "Hours": $(this).find("hours").text(),
                        "Contacts": {
                            "Phone": $.map($(this).find("phone").toArray(), function (item) {
                                return { "Type": $(item).find("type").text(), "No": $(item).find("no").text() };
                            })
                        }
                    };
                    customerInfo.push(loc);

                    // Reading and displaying a JSON object in HTML.
                    $("<li></li>").html("Name : " + loc.Name + "<br /> Contacts: <br />" + $.map($(loc.Contacts.Phone).toArray(), function (item) {
                        return item.Type + ": " + item.No + "<br/>";
                    }).join("")).append("<br>").appendTo("#dvContent ul");
                });
            });
        });    

    </script>
</head>
<body>
    <div id="dvContent">
    </div>
</body>
</html>



Tuesday, April 29, 2014 #

Lets take a sample XML file and name it as Meeting.xml.

<?xml version="1.0" encoding="utf-8"?>
<billing>
  <item>
    <id>1</id>
    <customer>Pavan Kumar Pabothu</customer>
    <type>Daily Scrum Call</type>
    <date>4/5/2012</date>
    <hours>1</hours>
    <contact>
       <phone>
        <no>979107</no>
        <type>home</type>
      </phone>
      <phone>
        <no>9999995929</no>
        <type>mobile</type>
      </phone>
    </contact>
  </item>
  <item>
    <id>2</id>
    <customer>Reddaiah Raju</customer>
    <type>Sprint Meeting</type>
    <date>3/20/2014</date>
    <hours>4</hours>
    <contact>
       <phone>
        <no>2375226</no>
        <type>home</type>
      </phone>
      <phone>
        <no>998884888</no>
        <type>mobile</type>
      </phone>
    </contact>
  </item>
  <item>
    <id>3</id>
    <customer>Kishan Chand Yadav</customer>
    <type>Daily Status Call</type>
    <date>4/20/2014</date>
    <hours>1</hours>
    <contact>
       <phone>
        <no>9988776652</no>
        <type>home</type>
      </phone>
      <phone>
        <no>9988776654</no>
        <type>mobile</type>
      </phone>
    </contact>
  </item>
</billing>

For the above XML we need to create entity objects as below

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string MeetingType { get; set; }
    public DateTime CallDate { get; set; }
    public int DurationInHours { get; set; }
    public Contact Contacts { get; set; }
}

public class Contact
{
    public List<PhoneContact> Phone = new List<PhoneContact>();
}

public class PhoneContact
{
    public string Type { get; set; }
    public string Number { get; set; }
}

And we can read the XML using below code.

// Using LINQ
private List<Customer> GetCustomerList()
{
    XElement xmlDoc = XElement.Load(Server.MapPath(@"~/Data/Meeting.xml"));
    var customers =
     from cust in xmlDoc.Descendants("item")
     select new Customer
     {
     ID = Convert.ToInt32(cust.Element("id").Value),
     Name = cust.Element("customer").Value,
     MeetingType = cust.Element("type").Value,
     CallDate = Convert.ToDateTime(cust.Element("date").Value),
     DurationInHours = Convert.ToInt32(cust.Element("hours").Value),
     Contacts = new Contact()
     {
     Phone = new List<PhoneContact>(from phn in cust.Descendants("phone")
select new PhoneContact
{
   Type = phn.Element("type").Value,
     Number = phn.Element("no").Value
})
     }
     };
    return customers.ToList();
}


// Using LAMDA
private List<Customer> GetCustomerList()
{
XElement xmlDoc = XElement.Load(Server.MapPath(@"~/Data/Meeting.xml"));

var customers =
xmlDoc.Descendants("item").Select(cust => new Customer
{
ID = Convert.ToInt32(cust.Element("id").Value),
Name = cust.Element("customer").Value,
MeetingType = cust.Element("type").Value,
CallDate = Convert.ToDateTime(cust.Element("date").Value),
DurationInHours = Convert.ToInt32(cust.Element("hours").Value),
Contacts = new Contact { 
Phone = cust.Descendants("phone").Select(phn => new PhoneContact { 
Number = phn.Element("type").Value, 
Type = phn.Element("no").Value 
}).ToList()
}
});

return customers.ToList();
}



Monday, May 20, 2013 #

When we launch the Notepad program in Windows, the program executes inside of a container known as a process. We can launch multiple instances of Notepad, and each instance will run in a dedicated process. Using the Task Manager application, we can see a list of all processes currently executing in the system.

A process contains the executable code and data of a program inside memory it has reserved from the operating system. There will be at least one thread executing instructions inside of the process, and in most cases there are multiple threads. If the program opens any files or other resources, those resources will belong to the process.

A process is also boundary. Erroneous code inside of a process cannot corrupt areas outside of the current process. It is easy to communicate inside of a process, but special techniques are required to communicate from one process to another. Each process also runs under a specific security context which can dictate what the process can do on the machine and network.  

A process is the smallest unit of isolation available on the Windows operating system. This could pose a problem for an ISP who wants to host hundreds of ASP.NET applications on a single server. The ISP will want to isolate each ASP.NET application to prevent one application from interfering with another company’s application on the same server, but the relative cost of launching and executing a process for hundreds of applications may be prohibitive.

Introducing the Application Domain

.NET introduces the concept of an application domain, or AppDomain. Like a process, the AppDomain is both a container and a boundary. The .NET runtime uses an AppDomain as a container for code and data, just like the operating system uses a process as a container for code and data. As the operating system uses a process to isolate misbehaving code, the .NET runtime uses an AppDomain to isolate code inside of a secure boundary.

Note, however, that the application domain is not a secure boundary when the application runs with full trust. Applications running with full trust can execute native code and circumvent all security checks by the .NET runtime. ASP.NET applications run with full trust by default.

An AppDomain belongs to only a single process, but single process can hold multiple AppDomains. An AppDomain is relatively cheap to create (compared to a process), and has relatively less overhead to maintain than a process. For these reasons, an AppDomain is a great solution for the ISP who is hosting hundreds of applications. Each application can exist inside an isolated AppDomain, and many of these AppDomains can exist inside of a single process – a cost savings.

AppDomains And You

You’ve created two ASP.NET applications on the same server, and have not done any special configuration. What is happening?

A single ASP.NET worker process will host both of the ASP.NET applications. On Windows XP and Windows 2000 this process is named aspnet_wp.exe, and the process runs under the security context of the local ASPNET account. On Windows 2003 the worker process has the name w3wp.exe and runs under the NETWORK SERVICE account by default.

An object lives in one AppDomain. Each ASP.NET application will have it’s own set of global variables: Cache, Application, and Session objects are not shared. Even though the code for both of the applications resides inside the same process, the unit of isolation is the .NET AppDomain. If there are classes with shared or static members, and those classes exist in both applications, each AppDomain will have it’s own copy of the static fields – the data is not shared. The code and data for each application is safely isolated and inside of a boundary provided by the AppDomain

In order to communicate or pass objects between AppDomains, you’ll need to look at techniques in .NET for communication across boundaries, such as .NET remoting or web services.

Note again: the one caveat to the idea of an AppDomain as a boundary is that ASP.NET applications will run with full trust by default. Fully trusted code can execute native code, and native code can essentially have access to anything inside the process. You’ll need to run applications with partial trust to restrict access to unmanged code and verify all managed code to secure AppDomains.

Shadow Copies and Restarts

Once an assembly is loaded into an AppDomain, there is no way to remove the assembly from the AppDomain. It is possible, however, to remove an AppDomain from a process.

If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain , it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests.

Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk.

The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline.

Master Of Your Domain

Application domains replace the OS process as the unit of isolation for .NET code. An understanding of application domains will give you an idea of the work taking place behind the scenes of an ASP.NET application. Using the CurrentDomain property of the AppDomain class you can inspect properties about the AppDomain your code is executing in, including the Shadow Copy settings we discussed in this article.

Source: http://odetocode.com/articles/305.aspx

Friday, May 18, 2012 #

Have you ever gotten errors when working with WCF services?

  1. Open up your web.config/app.config on the server side and add the following

    <system.diagnostics>
     <!-- This logging is great when WCF does not work. -->
     <sources>
      <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
       <listeners>
        <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "c:\traces.svclog" />
       </listeners>
      </source>
     </sources>
    </system.diagnostics>
  2. A file called traces.svclog will be stored on your harddrive. This will contain the the error message that you're looking for. All you now need is the right tool to open it up. It is calledsvctraceviewer.exe and usually resides in the folder C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin. If you don't have this folder or anything like it, you go download the Microsoft Windows SDK from here.
  3. Now you can open your log and look for the error that is thrown. There you will find a detailed stacktrace of what's wrong.



Sunday, October 16, 2011 #

ASP.NET view state, in a nutshell, is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks. View state has caused the most confusion among ASP.NET developers. When creating custom server controls or doing more advanced page techniques, not having a solid grasp of what view state is and how it works can come back to bite you. Web designers who are focused on creating low-bandwidth, streamlined pages oftentimes find themselves frustrated with view state, as well. The view state of a page is, by default, placed in a hidden form field named __VIEWSTATE. This hidden form field can easily get very large, on the order of tens of kilobytes. Not only does the __VIEWSTATE form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.

Here's an interesting, odd, but obvious idea. If you're not able to use HttpCompression like the Blowery HttpCompression module that we use with dasBlog due to the pile of bugs in older versions of IE around compression, you can "zip" up the ViewState on fat (usually DataGrid related bloat).

Using Zipped ViewState:

public class CompressedPage : PageViewStateZip

Just deriving from System.Web.UI.Page as usual:

public class RegularPage : System.Web.UI.Page

The "trick" is pretty simple. There are little-known virtuals in Page that you can override - specifically LoadPageStateFromPersistanceMedium (where that persistance medium is a hidden input box) and SavePageStateToPersistenceMedium.

When it's time to load view state, we pull it out of the form and un-base64 the string into a byte array, un-zip the bytes, then deserialize the ViewState. When it's time to save, reverse the process - Serialize, zip, store. There's some overhead, certainly. The amount of compression is usually about 50%, but your mileage may vary (YMMV).

Note that this sample uses SharpZipLib from ICSharpCode, but I assume you could use others, and I'd probably use System.IO.Compression if I was using .NET 2.0. The buffer sizes are hard-coded, but the only one that really matters it the one in Compress(). Again, salt to taste.


using System.IO;
using Zip = ICSharpCode.SharpZipLib.Zip.Compression;

/// <summary>
/// Summary description for vioZip
/// </summary>
public class vioZip
{
    public static byte[] Compress(byte[] bytes)
    {
        MemoryStream memory = new MemoryStream();
        Zip.Streams.DeflaterOutputStream stream = new Zip.Streams.DeflaterOutputStream(memory,new Zip.Deflater(Zip.Deflater.BEST_COMPRESSION), 131072);
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        return memory.ToArray();
    }

    public static byte[] Decompress(byte[] bytes)
    {
        Zip.Streams.InflaterInputStream stream = new Zip.Streams.InflaterInputStream(new MemoryStream(bytes));
        MemoryStream memory = new MemoryStream();
        byte[] writeData = new byte[4096];
        int size;
        while (true)
        {
            size = stream.Read(writeData, 0, writeData.Length);
            if (size > 0)
            {
                memory.Write(writeData, 0, size);
            }
            else
            {
                break;
            }
        }
        stream.Close();
        return memory.ToArray();
    }
}

Now create a base class for a page just as below

using System;
using System.Web;
using System.IO;
using Zip = ICSharpCode.SharpZipLib.Zip.Compression;
using System.Web.UI;

/// <summary>
/// Summary description for PageViewStateZip
/// </summary>
public class PageViewStateZip: System.Web.UI.Page
{
    protected override object LoadPageStateFromPersistenceMedium()
    {
        string vState = Request.Form["__VSTATE"];
        byte[] bytes = System.Convert.FromBase64String(vState);
        bytes = vioZip.Decompress(bytes);

        LosFormatter format = new LosFormatter();
        return format.Deserialize(System.Convert.ToBase64String(bytes));
    }

    protected override void SavePageStateToPersistenceMedium(object state)
    {
        LosFormatter format = new LosFormatter();
        StringWriter writer = new StringWriter();

        format.Serialize(writer, state);
        string viewStateStr = writer.ToString();

        byte[] bytes = System.Convert.FromBase64String(viewStateStr);

        bytes = vioZip.Compress(bytes);
        string vStateStr = System.Convert.ToBase64String(bytes);
        ClientScript.RegisterHiddenField("__VSTATE", vStateStr);
    }
}

Inherit this PageViewStateZip for all the webpages in your application.

public class CompressedPage : PageViewStateZip.

This article is C# version of the http://www.hanselman.com/blog/ZippingCompressingViewStateInASPNET.aspx.


Saturday, May 21, 2011 #

Below is how we can build a complex JSON in javascript and pass it to ASHX file.


$.toJSON(jsonData) looks like as below

[{"Name":"Pavan Kumar Pabothu","Age":27,"ID":361621},{"Name":"Reddaiah Raju Padhmaraju","Age":27,"ID":362541},{"Name":"Denish Raju Padhmaraju","Age":26,"ID":368941}]

Below is how you can read the object in ASHX page.


 


Thursday, March 17, 2011 #

public class Employees
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
}

List<Employees> employeeList = new List<Employees>();
List<Employees> resultList = new List<Employees>();
decimal maxSalary;
List<string> employeeNames = new List<string>();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        FillEmployees();
    }

    // Getting a max salary
    maxSalary = employeeList.Max((emp) => emp.Salary);

    // Filtering a List
    resultList = employeeList.Where((emp) => emp.Salary > 50000).ToList();

    // Sorting a List
    // To get a descending order replace OrderBy with OrderByDescending
    resultList = employeeList.OrderBy<Employees, decimal>((emp) => emp.Salary).ToList();

    // Get the List of employee names only
    employeeNames = employeeList.Select<Employees, string>(emp => emp.Name).ToList();
  
    // Getting a customized object with a given list
    var employeeResultSet = employeeList.Select((emp) => new { Name = emp.Name, BigSalary = emp.Salary > 50000 }).ToList();
}

private void FillEmployees()
{
    employeeList.Add(new Employees { EmployeeId = 1, Name = "Shankar", Salary = 125000 });
    employeeList.Add(new Employees { EmployeeId = 2, Name = "Prasad", Salary = 90000 });
    employeeList.Add(new Employees { EmployeeId = 3, Name = "Mahesh", Salary = 36000 });
}


Wednesday, March 9, 2011 #

If you are using SQL Server management Studio much the we can observer that the list of server names in the log in of it. As you can imagin a period of time after 6 month or 1 year you will see a long list of server names in the login dialog.

How to clear this list...?

I doesn't provide a mechanism to clean nor clear the list, so you'll have to do a little browsing through your file system.

For SQl Server 2005 Management Studio, we should delete the below file
C:\Documents and Settings\<user>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat.

For SQl Server 2008 Management Studio, we should delete the below file
C:\Documents and Settings\<user>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\SQLStudio.bin.


After deletion we can re-login the Management studio and can see the empty list.