Wednesday, June 5, 2013

NHibernate: Returning extra properties from stored procedure not in model

I was working on getting the data from two tables using a stored procedure in which resultset was a combination of fields coming from multiple tables. I created the domain model for one of the tables involved in the query in stored procedure and introduced the other fields pertaining to the other table in the same domain model class. I did provide the return property tag in the .hbm mapping file too, as shown below.  

After doing all this I got an error for the fields which were part of the other table for which only properties were added to the domain model class.
Solution:

 
UserData Class
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
using NameSpace.DAL.Base;
using NameSpace.DomainModel.Base;
using NameSpace.DomainModel.User;
using NHibernate;
using NHibernate.Criterion;

namespace NameSpace.DAL.User
{
    ///
    /// UserData class for doing DB operations related to User
    ///

    public partial class UserData : DataManagerBase
    {
        #region Constructors

        internal UserData()
            : base()
        {
        }

        ///
        /// Initializes a new instance of the class.
        ///

        /// The session.
        public UserData (INHibernateSession session)
            : base(session)
        {
        }
        #endregion Constructors

        #region Get Methods
        ///
        /// Method to get the User Info.
        ///

        ///
        ///
        public IList GetUserInfo()
        {
            IList lstUserInfo = null;
         
            try
            {
                IQuery Q = GetNamedQuery("User.GetUsers");
                lstUserInfo = Q.List();
             }
            catch (Exception ex)
            {
                 Your Exception Handling Code here.
            }

            return lstUserInfo ;
        }

 #endregion Get Methods
    }
}


User DomainModel Class

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

namespace Namespace.DomainModel.User
{
    ///
    /// Represents a User entity
    ///

    /// XYZ
    /// ABC
    /// TRT
    /// 05 June 2013

    public class User : EntityBase
    {
        #region Constructors

        ///
        /// Class constructor...
        ///

        public User()
        {
            //TODO:Write constructor stuff here..
        }

        #endregion Constructors

        #region Property Declarations

        public virtual int UserId
        {
            get
            {
                return base.Id;
            }
            set
            {
                base.Id = value;
            }
        }

        public virtual string FirstName { set; get; }

        public virtual string LastName { set; get; }

        public virtual string SearchCriterion { set; get; }
      
        #endregion Property Declarations

        #region ToString() Implementation

        ///
        /// This methods returns a string representation of this class.
        ///

        /// A string representation of this class.
        public virtual new string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(6);

            sb.AppendLine("------------User dump starts---------------");
            sb.AppendLine("UserId: " + (this.Id.ToString()));
            sb.AppendLine("FirstName: " + (this. FirstName != null ? this. FirstName: "").ToString());
            sb.AppendLine("LastName: " + (this. LastName!= null ? this. LastName: "").ToString());
            sb.AppendLine("SearchCriterion: " + (this. SearchCriterion!= null ? this. SearchCriterion : "").ToString());
sb.AppendLine("------------User dump ends---------------");
            return sb.ToString();
        }

        public override bool Equals(object obj)
        {
            //Same reference check !
            if (object.ReferenceEquals(this, obj)) return true;

            //Type check !
            User other = obj as User;
            if (other == null) return false;

            if ((Id == 0))
                //Do a per-property search
                return
                (FirstName == other.FirstName) &&
                (FirstName == other.FirstName) &&
                (SearchCriterion == other.SearchCriterion) ;
            else
                return Id == other.Id;
        }

        public override int GetHashCode()
        {
            return (this.GetType().FullName + Id.ToString()).GetHashCode();
        }

        #endregion ToString() Implementation
    }
}

Monday, April 1, 2013

Difference between Trace and Debug

  Common         
          Both Debug and Trace use System.Diagnostics namespace.

Trace
  1. It uses Trace class.
  2. Trace statement includes by default when program compiled into released build.
  3. Trace class is used for testing and optimization even after an application is compiled and released. 
  4. Trace class works in both case Debug mode as well as release mode.
  5. Trace runs in different thread form main program execute thread.
  6. For Trace we can use Trace.Write() method.  
  7. It uses time of application deployment.
  Debug
  1. It uses Debug class.
  2. It uses in debug build.
  3. It uses the time of application development.
  4. In Debug mode compiler inserts some debugging code inside the executable.
  5. Debug class works only in debug mode.
  6. Performance analysis cannot be done using Debug.
  7. Debugging uses to find error in program.
  8. For Debug we can use Debug.Write() method.
  9. Debug runs in same thread as main program execute.

Monday, February 18, 2013

Function to Split String in Chunks of Given Max Size

Friends,

Following is the function to split a given string in chunks of given maximum size:

 public static List SplitString(string stringToSplit, int maxLength)
        {
            List lstStr = new List();

            if (!String.IsNullOrEmpty(stringToSplit) && maxLength > 0 && stringToSplit.Length - maxLength >= 0)
            {
                int count = 0;
                for (int i = 0; i < stringToSplit.Length; )
                {
                    count = stringToSplit.Length - i >= maxLength ? maxLength : stringToSplit.Length - i;
                    lstStr.Add(stringToSplit.Substring(i, count));
                    i = i + maxLength;
                }
            }

            return lstStr;
        }

Tuesday, February 12, 2013

Creating a website in IIS7 programatically

This post will let you know about how to create a website in the IIS7 panel programatically.
For this purpose you need to add the reference to the Microsoft.Web.Administration found in the following paths depending on your system configuration:

C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
OR 
C:\Windows\SysWOW64\inetsrv\Microsoft.Web.Administration.dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Web.Administration;

namespace WebSiteCreator
{
    ///


    /// Interaction logic for MainWindow.xaml
    ///

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void CreateWebSite()
        {
            string siteName = txtSiteName.Text.Trim();
            string applicationPoolName = txtAppPoolName.Text.Trim();
            string virtualDirectoryPath = txtVDPath.Text.Trim();
            string virtualDirectoryPhysicalPath = txtVDPhysicalPath.Text.Trim();
            string ipAddress = txtIpAddress.Text.Trim();
            string tcpPort = txtPort.Text.Trim();
            string hostHeader = txtHostHeader.Text.Trim();
            string applicationPath = txtAppPath.Text.Trim();
            long siteId = 1;

            using (ServerManager servMgr = new ServerManager())
            {
                Site site = servMgr.Sites[siteName];

                if (site != null)
                    return;

                ApplicationPool appPool = servMgr.ApplicationPools[applicationPoolName];

                if (appPool == null)
                {
                    appPool = servMgr.ApplicationPools.CreateElement();
                    appPool.SetAttributeValue("name", applicationPoolName);
                }

                foreach (Site mysite in servMgr.Sites)
                {
                    if (mysite.Id > siteId)

                        siteId = mysite.Id;
                }

                siteId++;

                site = servMgr.Sites.CreateElement();

                site.SetAttributeValue("name", siteName);

                site.Id = siteId;

                site.Bindings.Clear();

                string bindingSetting = ipAddress + ":" + tcpPort + ":" + hostHeader;

                Microsoft.Web.Administration.Binding binding = site.Bindings.CreateElement();

                binding.Protocol = "http";

                binding.BindingInformation = bindingSetting;

                site.Bindings.Add(binding);

                Microsoft.Web.Administration.Application app = site.Applications.CreateElement();

                app.Path = applicationPath;

                app.ApplicationPoolName = applicationPoolName;

                Microsoft.Web.Administration.VirtualDirectory vdir = app.VirtualDirectories.CreateElement();

                vdir.Path = virtualDirectoryPath;

                vdir.PhysicalPath = virtualDirectoryPhysicalPath;

                app.VirtualDirectories.Add(vdir);

                site.Applications.Add(app);

                servMgr.Sites.Add(site);

                servMgr.CommitChanges();
            }
        }

        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            CreateWebSite();
        }
    }
}

Link to download the software - Download

Thursday, February 7, 2013

The specified service has been marked for deletion

When you get this message then chances are that you're trying to uninstall a windows service.
Generally, this error happens when you don't stop the service before attempting to uninstall it or/and some associated process or handle hangs around, preventing the service from being uninstalled.

One common reason for this happening is services.msc - you have to take care of it particularly as chances of getting this error are also when you have stopped the service before running your uninstaller, and still have the services.msc window open.

The name of the service will still be shown in the service listing if your services.msc window is open. So before trying to restart the system, make sure you close this window in your session and any other active rdp session.

If you close and reopen the services.msc window, you'll probably find that your service has now been successfully deleted.

Thursday, January 17, 2013

Object references an unsaved transient instance - save the transient instance before flushing

This issue generally comes when you have a collection in your entity, and that collection has one or more items which are not present in the database. It is usually resolved by setting cascade property in collection mapping to "all".

Thursday, December 13, 2012

WCF REST API and Optional Parameters


In case you are developing WCF REST API with GET operation and there is need to have provision for sending optional parameters, this post is for you. Earlier Microsoft doesn't support this however with .NET Framework 4.0 this works smoothly. I will show you how:

For example there are three parameters(id, language, mode) that are always passed in the url and other one(type) is optional.

Request URL could be like this:
or

Handling at Service side will be as follows:

 [ServiceContract]
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
   
    public class MyService
    {
        [WebGet(UriTemplate = "?id=ID&language=LanguageCode&mode=free")]
        public string GetValue(string id, string language, string mode)
        {
            var type = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["type"];
            if(type!=null)
     {
return "Hi There " + ID + " " + LanguageCode + " " + mode + " " + type;
     }
     else
     {
return "Hi There " + ID + " " + LanguageCode + " " + mode;
     }

        }
    }

Request URL could be like this:
or

Handling at Service side will be as follows:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
   
    public class MyService
    {
        [WebGet(UriTemplate = "id/{ID}/language/{LanguageCode}/mode/{mode}")]
        public string GetValue(string ID, string LanguageCode, string mode)
        {
            var type = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["type"];
            if(type!=null)
     {
return "Hi There " + ID + " " + LanguageCode + " " + mode + " " + type;
     }
     else
     {
return "Hi There " + ID + " " + LanguageCode + " " + mode;
     }
        }
    }

Hope it helps you.