Saturday, 30 May 2015

Bind Data to DataGridview using Lamba expression

If we want to bind list of objects to datagridview using coding ,we can do that by using
the following approach :-

For e.g:- If we have list of custom class that we want to bind to datagridview
List<ClassName> searchList;
 this.transactiondataGridView.DataSource = searchList.Select(x => new

{

    x.TrustAccount.Code,
 
    x.Amount,

    x.Payor,

    x.SettlementDate,

    x.PropertyAddress,

    x.Borrower

}).ToList();






                   


 




 

Wednesday, 27 May 2015

Adding file structure using treeview

  private void ListDirectory(TreeView treeView, string path)
        {
            treeView.Nodes.Clear();
            var rootDirectoryInfo = new DirectoryInfo(path);
            treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
        }

        private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
        {
            var directoryNode = new TreeNode(directoryInfo.Name);
            foreach (var directory in directoryInfo.GetDirectories())
                directoryNode.Nodes.Add(CreateDirectoryNode(directory));
            foreach (var file in directoryInfo.GetFiles())
                directoryNode.Nodes.Add(new TreeNode(file.Name));
            return directoryNode;
        }

Wednesday, 6 May 2015

Binding List to datagridview using LINQ


List<string> listFiles=new List<string>();
//FIll your list with data that you want to display in datagridview

documentsDataGridView.DataSource = listFiles.Select(x => new { ColmnName1 = Path.GetFileName(x), ColumnName2 = x }).ToList();

//This will create two columns in datagridview with the name as :-ColmnName1 /ColmnName2
 

Tuesday, 5 May 2015

Merging Two rows in sql

How to combine two or more rows corresponding to same id to remove duplicate rows


step 1 : Create Table #EscrowNo(rootId int,reference nvarchar(50))

steo2 : insert into #EscrowNo (select distinct RootId# ,

STUFF((Select ','+ReferenceNumber

from [pfm].[Contact] pfmEscrow)

where pfmEscrow.RootId#=pfmEscrow2.RootId#

FOR XML PATH('')),1,1,'') from [pfm].[Contact] pfmEscrow2

step 3 : select * from #EscrowNo

Result:
You have merged all the rows corresponding to similar id in one row

Monday, 4 May 2015

How to delete duplicate rows table in sql

Deleting duplicate rows

e.g:- Suppose that we have a table named "Employees" having auto increment id and we want to delete latest duplicate row. In the following table we would like to delete the latest duplicate salary row, which in this case is [id=3,name=f,salary=200]




DELETE FROM [Data].[dbo].[employees] 
WHERE  id IN (SELECT TOP(1)id 
              FROM   [Data].[dbo].[employees] 
              WHERE  salary IN (SELECT salary 
                                FROM   [Data].[dbo].[employees] 
                                GROUP  BY salary 
                                HAVING Count(*) > 1) 
              ORDER  BY id DESC) 

After executing this query you will get a table without any duplicate salary



Thursday, 30 April 2015

Sql query to find Nth highest salary using TOP

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary

finding the 2nd highest salary in SQL

SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

SQL :- How to find nth highest salary

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

Friday, 20 March 2015

Mvc DbUpdateConcurrencyException

Exception :-DbUpdateConcurrencyException thrown:-

Solution :-

If you have manually created the table in the database, then delete it and let the entity framework made the table
automatically.

Run the following command in the nudget console :-
PM>enable-migrations -ContextTypeName EmployeeContext

PM>add-migration InitialCreate

PM>update-database -verbose

MVC NullReference Exception


1. Null Reference Exception :-


Null reference exception occurred at view page because you have not passed the model object from the controller class to
the respective view page

e.g:-
public ActionResult Index()
{
            Customer obj = new Customer();
            obj.id = 1001;
            obj.name = "raju";
            return View("index");//--->this will inoke the view index.aspx
}

[index.aspx]
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcCustomer.Models.Customer>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        The customer id is <%=Model.id %> //-->Model is used to bind view with Model objects
        The customer name is <%=Model.name %>
    </div>
</body>
</html>

//This will cause "NullreferenceExceptoin" error at view page because you have not passed the model object from the
controller to the view page

solution :- Pass the object in the view as follows:-
public ActionResult Index()
{
            Customer obj = new Customer();
            obj.id = 1001;
            obj.name = "raju";
            return View("index",obj);//--->this will invoke the view index.aspx
}


Friday, 13 March 2015

WCF SERVICE CONFIGURING


Configure your WCF service in "web.config" as below ;-
[web.config]

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="web"
                 receiveTimeout="00:30:00"
                 sendTimeout="00:30:00"></binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="namespace.serviceName"  behaviorConfiguration="web">
        <endpoint name="mex" address="" binding="basicHttpBinding"         contract="namespace.serviceInterface">
        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="web">
          <!-- To enable metadata information -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details  -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

[Iservice1.cs]
using System.ServiceModel;
using System.ServiceModel.Web;

namespace namespaceName
{
 
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "/method1/{arg1}", ResponseFormat =    WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]

        string method1(string arg1);

        [OperationContract]
        [WebInvoke(UriTemplate = "/method2/{arg1}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string method2(string arg1);
    }

}

[Service1.svc]
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

namespace NamespaceName
{
    public class Service1 : IService1
    {
        public string method1(string arg1)
        {
            //do implementation here
        }

        public string method2(string arg1)
        {
             //do implementation here
        }
    }
}

Note:deploy/publish the service as mentioned in other posts

WCF


What is WCF?

WCF stands for windows communication foundation. WCF is a feature which is made available by the Microsoft for building distributed and inter-operable applications.

Distributed applications:
--------------------------------
Distributed application is an application where parts of it run on more than one computer.In distributed applications some part of the application may reside on one system while other parts of application may reside on other systems.

For e.g:- A client machine of any user is accessing the web service of other third party which may be sitting miles away from the client machine.

Distributed systems provide the better scalablity for the applications, which means that the if a application is large enough to be reside on one machine than it can divided to different tiers. These tiers can be Presentation tier,business tier and data access tier.

Inter-operable applications
----------------------------------
Sometimes we have a client which may be running java on its client machine and our service may be built in .net platform then how will a java client will be able to access the .net service.
This is where an inter operable application comes in play. An inter operable application makes it possible for any platform to communicate with each other.

Why we use WCF?

Previously we were having web services to deploy the services but we need the separate technology like "remoting" if we want to deploy "tcp protocol", but Microsoft has eradicated that headache of learning separate technology. You can now do all the service stuff by using WCF only.

for e.g:- if you have 2 clients and if one client wants to access your service by using the following format:-
-HTTP PROTOCOL WITH XML MESSAGE FORMAT

and there is 2nd client who wants to access your service by using the following format:-
TCP PROTOCOL WITH BINARY MESSAGE

then instead of making the remoting services for 2nd client, we can just use the same wcf service by adding the 2nd endpoint for the 2nd client.

In the endpoint configuration, we can specify the format of messages and protocols

With this we are having only single service and this service ,we can deploy multiple endpoints for multiple clients.





PUBLISH WCF SERVICE


1.CREATE A NEW PROJECT AND ADD A WCF SERVICE APPLICATION

2.THIS WILL ADD A SERVICE PROJECT WITH TWO CLASSES. ONE OF INTERFACE TYPE AND ANOTHER CLASS WHICH IMPLEMENTS THE INTERFACE CLASS.
THE SERVICE CLASS WHICH IS IMPLEMENTING THE INTERFACE CLASS WILL BE HAVING A .SVC EXTENSION WHICH MEANS IT IS YOUR SERVICE CLASS

3.NOW TO PUBLISH THIS SERVICE ,YOU CAN EITHER RUN YOUR SERVICE PROJECT BY CLICKING THE "PLAY" BUTTON OR HITTING "F5" OR "CTRL+F5"
 OR
BY PUBLISHING THE WCF SERVICE USING THE IIS MANAGER

HOW TO PUBLISH WCF SERVICE USING IIS MANAGER?

1. OPEN YOUR IIS MANAGER FIRST BY TYPING "inetmgr" IN YOUR RUN WINDOW.
IIS MANAGER WILL LOOK SOMETHING LIKE THE BELOW IMAGE :-

2. NOW RIGHT CLICK THE "SITES" FOLDER AND CLICK THE "ADD WEBSITE"
3.MENTION THE SITE NAME AND PHYSICAL PATH WHERE YOUR SERVICE WILL BE LOCATED.
IP ADDRESS WILL BE YOUR LOCAL MACHINE IP ADDRESS OR "LOCALHOST" BY DEFAULT.

4. YOU NEED TO METION THE PORT NUMBER APART FROM LOCAL PORT NUMBER WHICH IS "80".

5.CLICK THE "OK" BUTTON AND YOUR SERVICE WEB SITE WILL BE CREATED AT YOUR MENTIONED PHYSICAL PATH.

6.FOR E.G:- I HAVE CREATED THE WEB SITE "SITENAME" WHICH YOU CAN SEE IN THE IIS MANAGER WINDOW. AT THE RIGHT HAND SIDE YOU CAN SEE THE OPTION OF "RESTART,START,STOP" UNDER THE "MANAGE WEBSITE". FROM HERE YOU CAN START OR STOP YOUR SERVICE.

RIGHT CLICK YOUR SITE NAME AND GO TO THE OPTION "MANAGE WEBSITE". FROM HERE YOU CAN BROWSE YOUR WEBSITE. YOU CAN ALSO START/STOP YOUR SERVICE FROM HERE.

YOUR SERVICE FOLDER WILL LOOK SOMETHING AS BELOW :-
THIS WILL CONTAIN YOUR SERVICE1.SVC AND WEB.CONFIG FILE OF YOUR SERVICE.

7. NOW GO TO YOUR SERVICE PROJECT IN THE VISUAL STUDIO AND BUILD THE PROJECT.

8.RIGHT CLICK YOUR PROJECT AND GO TO THE "PUBLISH" OPTION. FROM THERE CHOOSE THE "TARGET LOCATION" UNDER THE "CONNECTION" SECTION.
BROWSE THE PATH WHERE YOU HAVE SAVED YOUR WEBSITE [E.G:- E:\FILE1].

9.CLICK "NEXT" BUTTON AND CLICK THE "PUBLISH" BUTTON TO PUBLISH YOUR WEB SERVICE.

10.NOW TO CHECK IF YOUR SERVICE IS RUNNING, RIGHT CLICK YOUR WEBSITE IN IIS MANAGER AND CLICK THE BROWSE AND IN THE ADDRESS BAR ADD YOUR SERVICE NAME AFTER THE IP ADDRESS.
FOR E.G: LOCALHOST:88/SERVICE1.SVC
IF YOU ARE SEEING BELOW IMAGE IN YOUR PAGE, THAT MEANS YOUR SERVICE IS WORKING FINE !!


Thursday, 12 March 2015

Exception :- Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied solution Administartot tools>component services> 1.Go to Administrator tools 2.Then go to component services 3.open the Computers>my computer>DCOM config 4.search the microsoft word and assign the admin permission to it 5.In microsoft word go to Security -> Customize all 3 permissions to allow everyone For more information you can visit the follwoing url : http://stackoverflow.com/questions/17785063/retrieving-the-com-class-factory-for-component-error-80070005-access-is-de https://social.msdn.microsoft.com/Forums/vstudio/en-US/b401459a-d14a-4517-b204-fe7c0f5b1f83/retrieving-the-com-class-factory-for-component-with-clsid-000209ff00000000c000000000000046?forum=netfxbcl

Solution :-

Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied

solution

Administrator tools>component services>

1.Go to Administrator tools
2.Then go to component services
3.open the Computers>my computer>DCOM config
4.search the microsoft word and assign the admin permission to it
5.In microsoft word go to Security -> Customize all 3 permissions to allow everyone

For more information you can visit the follwoing url :
http://stackoverflow.com/questions/17785063/retrieving-the-com-class-factory-for-component-error-80070005-access-is-de


https://social.msdn.microsoft.com/Forums/vstudio/en-US/b401459a-d14a-4517-b204-fe7c0f5b1f83/retrieving-the-com-class-factory-for-component-with-clsid-000209ff00000000c000000000000046?forum=netfxbcl

How to get local ip address of host in c#



public string LocalIPAddress()
 {
   IPHostEntry host;
   string localIP = "";
   host = Dns.GetHostEntry(Dns.GetHostName());
   foreach (IPAddress ip in host.AddressList)
   {
     if (ip.AddressFamily == AddressFamily.InterNetwork)
     {
       localIP = ip.ToString();
       break;
     }
   }
   return localIP;
 }



To get ip address of local host

Tuesday, 10 March 2015

Hosting WCF services in console application

Adding and hosting WCF services in console application

1. Create a New "class library" project and add a new item in this project as "wcf service"
2. Add the new "console project" in your solution
3.Add the service refernece to your "console project"
4.Add the system.servicemodel reference to your project
5.Add the "app.config" to your project
6.Code "App.config" as :-
//<App.config>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="namespace.Name_of_Service" behaviorConfiguration="Name_of_behavior">
        <endpoint address="Name_of_Service" binding="basicHttpBinding" contract="namespace.Name_of_ServiceInterface"></endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/"/>
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="Name_of_behavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>
</configuration>

7.Make your "console project" as startup project and code the program.cs as :-

 public static void Main(string[] args)
        {
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(Namespace.Name_of_Service)))
                {
                    host.Open();
                    Console.WriteLine("Host started @" + DateTime.Now.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Friday, 27 February 2015

How to add a trusted publisher for your software


The advantage of the trusted application deployment is that you can run the application/software with  a high level of trust.
It will resolve the "Unknown publisher" error that you are encountering during the deployment of your application/software.




Publisher certificates are like a unique public-private key pair.

The organization that is granting the certificate is known as Certificate Authority(CA) or certificate issuer.
The organization to which the CA is granting the certificate is known as the publisher.


There are various companies which are providing/issuing certificates to the organizations. These companies will verify the identity of  organizations to which they are issuing the certificates.

Verisign and thawte are some of the well known examples of the companies who are providing the services of issuing certificates to legitimate the publisher.

You can visit the Verisign site by using the below link :

Wednesday, 25 February 2015

Adding Installers in your project using InoSetup


What is Innosetup Installer ?
It is used to create a installer for your project. For e.g: You are delivering a project to a client, but a client cannot register the service of its own or can execute the sql queries. To resolve this issue, we can make the installers which will register the services automatically and can run batch files which will execute sql queries automatically.

[Inosetup installer]
Inosetup

Steps to work with Inosetup installer in c#:-

1.Install the Inosetup
2.Add the .iss file in your solution projects
For e.g:- If you are having three projects[Client,Service,Shell] in your solution project then you need to add three installer[.iss] files per project
3. In your client project add the "Common.iss" installer which contains the common functionalities of the installers like the installer pop-up windows.
4.In your service project you will have installer file which will help you to register the .xml config file.
Your service installer[.iss] file will basically have a procedure which will execute the [.xml] config file.
E.g:-
procedure AfterInstallBatch();
begin
if     ExecBatch('Registering Warranty Title Tools Server Package...',  ExpandConstant('{app}\sps.exe'),         ExpandConstant('register /server:{code:GetSPServerInfo|Address} /user:{code:GetSPServerInfo|Username},{code:GetSPServerInfo|Password} ProjectServiceRegistration.xml'))

5.In your shell[U.I part of the project]project, you will add the projectname.Shell.Install.iss which will basically copies the ProjectName.client.dll and ProjectName.Shell.dll of your project from the bin folder to the softwares service directory which you want to integrate with your project.

Download .iss installer files [replace projectname with your project names]

Add the Installer\common.iss in your client project :-
common.iss

Add the Installer\projectname.service.install.iss in your client project :-
Service Installer
Add the Installer\projectname.shell.installer.iss in your shell project
Shell installer

Tuesday, 24 February 2015

CODING STANDARDS AND NAMING CONVENTIONS

 Explicitly declare the scope of the event delegate e.g:- private

 Private class level variable names should have preceding _(underscore) on them

 Private class member variable names should start with lower case character

 Delegate Method Names should start with Upper case character

 Remove _(underscore) from property names, make the property names indicate what they are for

 public property should not start with a _ and lower case char

 use  " this." before accessing any class level variable

 Declare scope, and move the variable declaration with others

 If we are not utilizing catch then don't use try block let the exception propagate to the calling code

 Properly Format the message shown in message box, with title,icon, button & a properly formatted message string

 Private properties should be names like a normal property

 If Properties are not used outside the class why not declare them as variables instead.


Monday, 23 February 2015

How to get Enum Description

For e.g:- If you a enum as follows:-

public enum EnumName
{
   [Description("Description1 of value1")]
   value1,
   [Description("Description2 of value2")]
   value2,
   [Description("Description3 of value3")]
   value3
}

//To fetch the description e.g["Description1 of value1"] from value1 of enum :-

using System;
using System.Reflection; // for FieldInfo 

using System.ComponentModel; // for DescriptionAttribute

static void Main(string[] args)
 {
            string desc1 = ToDescription(EnumName.value1);
            Console.WriteLine("the description is [value1]:" + desc1);
 EnumName val1=GetValueFromDescription<EnumName >(desc1);

           Console.WriteLine("the description is :" + val1);
}

//It will fetch description from enum value
 public static string ToDescription(object value)
  {
      FieldInfo field =value.GetType().GetField(value.ToString());
      DescriptionAttribute[] attributes =(DescriptionAttribute[])field
      .GetCustomAttributes(typeof(DescriptionAttribute), false);
       if (attributes.Length > 0)
        {
                return attributes[0].Description;
        }
            return value.ToString();
  }
//it will fetch value from description:-

 public static EnumName GetValueFromDescription<EnumName>(string description)
{
            var type = typeof(EnumName);
            if (!type.IsEnum) throw new InvalidOperationException();
            foreach (var field in type.GetFields())
            {
                var attribute = Attribute.GetCustomAttribute(field,
                    typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attribute != null)
                {
                    if (attribute.Description == description)
                        return (EnumName)field.GetValue(null);
                }
                else
                {
                    if (field.Name == description)
                    return (EnumName)field.GetValue(null);
                }
            }
            throw new ArgumentException("Not found.", "description");
            // or return default(call);

}



Creating and Importing VM

HOW TO ADD AUTOMATIC VERSION UPDATER IN C#?

Adding version updater for Assembly files in projects:-
=====================================================

 STEP 1:
----------
1. Add a new folder[e.g- utils] in your project solution and add a updateversions.exe file
2. Add the same file in the physical location as well.
3. You need to provide the path of all assemblies for which you want to change the versions.
4. Add versions.txt file in a new folder[e.g:-Solution item] in your project solution
5. Add same file in physical location as well.

STEP 2 :
----------
1. Next you need to add the locaion of your updateversions.exe in the Properties\"BUILD EVENTS"
 of your client project.
2.In the "Pre-build event command line" of build events, write the following code:-
if $(ConfigurationName) == Release (
"$(SolutionDir)"utils\updateversions.exe "$(SolutionDir)")
3. Now run the project in "Release" mode and your updater will update the assembly version
as you desired

UPDATEVERSION.EXE
versions.txt
 

Monday, 9 February 2015

HOW TO SET LOGIN IN SQL DATABASE


To set the Login in Ms-Sql Server :-
1.Open the SQl serer using your Administrator profile.
 
2.Go to Security>logins
3.Right click on login and select "New Login"
4.Click "search" button and a pop-window will open as follows:-



5.Now click the "Advanced" button and the following window will pop-up :-



6.Click the "Find Now" button.
7.In search results arera, list of profile names will be loaded. Select your profile from which you want to access the sql server and click the "ok" button.
8.Under "server roles" and "user mappings" check the checkboxes to grant the rights to your selected profile.