Pages

Jul 23, 2012

How to open Rad Window on page load from Code Behind.

Rad Window on PageLoad:
using Telerik.Web.UI;
     RadWindow newWindow = new RadWindow();
     newWindow.NavigateUrl = "Test.aspx";
     newWindow.VisibleOnPageLoad = true;
     newWindow.Modal = true;
     newWindow.Width = 750;
     newWindow.Height = 480;
     RadWindowManager1.Windows.Add(newWindow);

Apr 16, 2012

How to set Identity column value start from certain value + SQL

Below is the SQL query to get the  to set Identity column value start from certain value

DBCC CHECKIDENT ( 'TestDB.dbo.TestTable',RESEED, 1000000)

Mar 7, 2012

How to get fields & assigned domains of FeatureClass + ESRI + C#

here is the code to get fields of a featureclass and check for the assigned domain 

IFields fields = featureClass.Fields;
string domainName = string.Empty;
for (int i = 0; i < fields.FieldCount; i++)
{
if (fields.get_Field(i).DomainFixed)
domainName = fields.get_Field(i).Domain.Name;
}

Thanks
Mukund

Mar 6, 2012

How to get feature class from the shape file on Disk.

Below is the method that gets the feature class from the shape file
/// Get the FeatureClass from a Shapefile on disk (hard drive).
/// A System.String that is the directory where the shapefile is located.
Example: "C:\data\USA"

/// A System.String that is the shapefile name.
 Note: the shapefile extension's
///(.shp, .shx, .dbf, etc.) is not provided! Example: "States"</param>

public ESRI.ArcGIS.Geodatabase.IFeatureClass GetFeatureClassFromShapefileOnDisk
(System.String string_ShapefileDirectory, System.String string_ShapefileName)
{
     System.IO.DirectoryInfo directoryInfo_check = new System.IO.DirectoryInfo(                         
                                                                                 string_ShapefileDirectory);
      if (directoryInfo_check.Exists)
    {
        //We have a valid directory, proceed
        System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(string_ShapefileDirectory + "\\" +           
                                                                     string_ShapefileName + ".shp");
    if (fileInfo_check.Exists)
   {
        //We have a valid shapefile, proceed

         ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory =
                                                 new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); 
         ESRI.ArcGIS.Geodatabase.IWorkspace workspace =      
                                                 workspaceFactory.OpenFromFile(string_ShapefileDirectory, 0); 
         ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace =
                                                  (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace;
       // Explict Cast

        ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = 
                                                featureWorkspace.OpenFeatureClass(string_ShapefileName);
        return featureClass;
}
else
{
     //Not valid shapefile
      return null;
}
}
 else
{
    // Not valid directory
       return null;
}
}

How to find feature count that intersect an envelope in Geodatabase + C#

In our previous post, we discussed about connecting the File GeoDB and returning the Workspace.

Now will see how to find feature count that intersect an envelope in the File GeoDB

// The method FileGdbWorkspaceFromPropertySet definition is present in our previous post

IWorkspace featureWorkspace = FileGdbWorkspaceFromPropertySet(gdbPath);
        IFeatureWorkspace fws = (IFeatureWorkspace)featureWorkspace;

// Method that Gets Features Count From a FeatureClass

private static int GetCountFromFeatureClass(IFeatureWorkspace fws, string parcelName, IEnvelope envelope)
    {
        // Open the feature classes used by the queries.
        IFeatureClass parcelsFeatureClass = fws.OpenFeatureClass(parcelName);      

        //// Create the spatial filter. Note that the SubFields property specifies that only
        //// the Shape field is retrieved, since the features' attributes aren't being inspected.
        ISpatialFilter spatialFilter = new SpatialFilterClass();
        spatialFilter.Geometry = envelope;
        spatialFilter.GeometryField = parcelsFeatureClass.ShapeFieldName;
        spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
        spatialFilter.SubFields = "Shape";

        // Use IFeatureClass.FeatureCount to get a parcel count.
        return parcelsFeatureClass.FeatureCount(spatialFilter);

    }


Feb 15, 2012

How to connect to a ESRI Geodatabase and return workspace.

Initialize Product License with License Initializer

Connecting to GeoDB is the first step of querying the GeoDB. Inorder to work with the ArcObjects, the ArcGIS license has to be initialized. ESRI provides a License initializer project downloaded from the below link.


http://edn.esri.com/index.cfm?fa=codeExch.sampleDetail&pg=/arcobjects/9.1/Samples/Licensing_and_Extension_Checking/InitializeProductLicenseWithLicenseInitializer/InitializeProducLicenseWithLicenseInitializer.htm


Download the Project and add it to your solution which uses arcObjects. Set the Project InitializeProductLicense as the startup and run the project. Debug and see what is the license status returned.


below are the different cases returned

//esriLicenseAvailable                 
//esriLicenseNotLicensed
//esriLicenseFailure                   
//esriLicenseAlreadyInitialized                  
//esriLicenseNotInitialized
//esriLicenseCheckedOut                    
//esriLicenseCheckedIn
IF the return value is isriLicenseCheckedOut, then license is intialized.     
Below is the method that get path of the geoDB say C:\\test\\Test.gdb and returns the workspace that can be queried for different scenarios.              
Namespace Used:

using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geometry;


public static IWorkspace FileGdbWorkspaceFromPropertySet(String path)
        {
            //Initialize the application.
            esriLicenseStatus licenseStatus = esriLicenseStatus.esriLicenseUnavailable;
            IAoInitialize m_AoInitialize = new AoInitializeClass();
            licenseStatus = m_AoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);
          
            Type factoryType = Type.GetTypeFromProgID(
            "esriDataSourcesGDB.FileGDBWorkspaceFactory");
            IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2)Activator.CreateInstance
                (factoryType);
            return workspaceFactory.OpenFromFile(path, 0);
        }


In the next post will see how to query parcels intersecting a envelope in the GeoDB.

Dec 8, 2011

How to set html link visible false depending on Eval function in grid view

Below is the html link in the grid view item template that sets visibility depending on the IsOnline values.

<a href = "www.google.com" style='<%# Eval("IsOnline").ToString() == "True" ? "display:block" : "display:none" %>' >link</a>

Dec 7, 2011

How to convert DateTime to Date in Linq to Entity + C#

Use EntityFunction to truncate the time part from a DateTime String.

grid.DataSource = (from user in context.Users where ISActive = True select new
                                          {
                                              user.UserId,
                                              user.UserName,
                                              FirstName = (user.FirstName + " " + user.LastName),                                           
                                              CreatedDate = System.Data.Objects.EntityFunctions.TruncateTime(user.CreatedDate)                                           
                                          }).ToList();)

Jun 19, 2011

Clipboard operations in javascript


Copy TO and Copy FROM CLIPBOARD :


<body>
    <textarea id='clipText'>
Enter Text And Click Button To Copy Text To ClipBoard</textarea><br />
    <input type="button" id='bt' onclick="clipboardData.setData('Text',document.getElementById('clipText').value);"
        value="Copy" />
    <input type="button" onclick="clipboardData.clearData('Text');" value="Clear" />
    <input type="button" onclick="alert(clipboardData.getData('Text'));" value="Paste" />
</body>

May 26, 2011

How to insert a Guid or UniqueIdentifier and return it as a OUTPUT parameter + StoredProcedure. + SQL


CREATE PROCEDURE [test]
    @name as varchar(50),
    @id as uniqueidentifier OUTPUTAS
BEGIN
    declare @returnid table (id uniqueidentifier)

    INSERT INTO test(
        name
    )
    output inserted.id into @returnid
    VALUES(
        @name
    )

    select @id = r.id from @returnid rEND
Above SP returns the newly inserted GUID as the OUT parameter.

May 20, 2011

How to use double coute in string + C#

This usage of double coutes in a string can be easily done using @.
For eg:
To show the below text 
 "This is a "Test"


Code:
TextBox1.text = @"""This is a " + @"""Test""";


The logic is that if you use @ in front of the sting variable then using e double coute(""") 
throughout the string will give you one double coute(").

How to create a text file and save it on client machine using Save File Dialog + Asp.Net + C#

Method to Create text file:
Using System.IO;
Using SystemsText;

private void CreatetxtFile()
{
StringBuilder sb = new StringBuilder();

sb.AppendLine("test");
sb.AppendLine("= = = = = =");
sb.AppendLine();
sb.Append("test2");
sb.AppendLine();
sb.AppendLine();

using (StreamWriter outfile = new StreamWriter("c:" + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}

}
Code to Save the file as dialog :
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=AllTxtFiles.txt");
// specify the path of the file that has to be saved in client machine.
Response.TransmitFile("c://AllTxtFiles.txt");
Response.End();
The above code will show a save file dialog to save the file.

Apr 25, 2011

How to update data from excel sheet to the sql data base. + How to compare two date time columns and find the later values

// Copies the excel sheet values to the table sTemp.
SELECT * INTO dbo.sTemp
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test.xls;IMEX=1',
'SELECT * FROM [Sheet_Name2$]')

GO

// Compares two columns of the excel and updates the table with the later values.
UPDATE INV
SET
INV.EndDate = TMP.
RecentDate 
FROM
dbo.Inventory as INV
INNER JOIN
(
SELECT
Inventoryid,
CASE
WHEN ISNULL([WEDate],'') >= ISNULL([MEDate],'')
THEN
[WEDate]
ELSE
[MEDate]
END
AS MostRecentDate,
[WEDate],
[MEDate]
FROM sTemp
) TMP
ON
TMP.TestID = INV.TestID

GO

DROP TAble stemp

GO

Oct 4, 2010

How to find First non repeated character in a string + c#

This is really a mind twisting question. But if you dint give a try to solve this , you may think that its so simple.
This was asked in one of my interview.
now lets see how to solve this
Method call : GetFirstNonRepeatedChar("abcdab");

private char GetFirstNonRepeatedChar(string value)
        {
           // declare a character array.
            char[] cArr = null;
            try
            {
                // load the string to char array.
                cArr = value.ToCharArray();


                for (int i = 0; i < cArr.Length; i++)
           { 
                   // count to track all comparison has over              
                   int count = 0;
for (int j = 0; j < cArr.Length; j++)
                    {
                        // avoids to comparison for same character
                        if (i != j)
                        {
                            // if repeated then come out of the inner loop
                            if (cArr[i] == cArr[j])
                            {                                
                                break;
                            }
                            else
                            {
                                // increament the count for each non repeatable comparison
                                count = count + 1;
                                // if the count reaches the char array length - 1
                                // and you are inside the for loop then the current value
                                // is the first non repeated character.
                                if (count == cArr.Length -1)
                                {
                                    return cArr[i];
                                }
                            }
                        }                        
                    }
       }
                return '0'; // if no non repeated char is fount
            }
            catch (Exception)
            {
                
                throw;
            }            
        }


Answer : c

Oct 2, 2010

Difference between exec and sp_executesql + SQL SERVER

If we are using Direct T-SQL (not dynamic) in stored procedure, SQL Server reuses execution plan from the cache. i.e. SQL Server will not compile the Stored Procedure again.

If we are using dynamic sql in stored procedure, SQL Server may not use the execution plan. It will recreate the execution plan every time with different string of SQL.So, we have to think about the performance while using dynamic sql.

To execute the dynamic SQL in stored procedure, we have to use the following way.

1. EXEC (Non- parameterized)
2. sp_executesql (Parameterized)


There will be performance difference between above two.

Execution plan will not be created until you execute the dynamic sql. If you execute the dynamic sql using EXEC, execution plan will be created for every execution even values only changing. If you use sp_executesql, SQL Server Optimizer will try to use same execution plan. Because dynamic sql string will be the same, values only going to change. So it will be treated as Stored Procedure having input parameters.

Sep 30, 2010

Stored Procedure(SP) Vs User Defined Functions(UDF) + SQL SERVER

Differences: 
1. Procedure can return zero or n values whereas function can return one value which is mandatory.
2. Procedures can have input,output parameters for it whereas functions can have only input parameters.
3. Procedure allow select as well as DML statement in it whereas function allow only select statement in it.
4. Functions can be called from procedure whereas procedures cannot be called from function.
5. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
6. We can go for transaction management in procedure whereas we can't go in function.
7. Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.

Sep 9, 2010

How to specify table name dynamically in a SQL statement + SQL SERVER 2008

Dynamic SQL :
Using a dynamic sql is quite comman in sql statement. I had a situation where
i have to pass the table file as a argument to a Stored Procudure and depending 
upon the argument i have to execute the Select statement.


Say for eg.
argument @Table = dbo.Customers
then
SELECT * FROM @Table
But this doesnt work.
So when you are in a need to specify any of the objects like table or column etc
we need to use dynamic SQL using exec method. Below is an example

DECLARE @TableName varchar(50)
SET @TableName ='dbo.Customers'
DECLARE @SQL varchar(max)
SET @SQL = 'SELECT * FROM ' +@TableName // dynamic table name
EXEC(@SQL)

Sep 8, 2010

How to find the intersected rows of a spatial Index using POLYGON object + Spatial Queries

Below is the sample stored procedure used to find the 
rows that are intersected with the POLYGON object
[Created using Coordinates list].


CREATE PROCEDURE [dbo].[GetIntersectingRows] 
-- Add the parameters for the stored procedure here
@Coordinates varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;


Declare @AOIPolygon geography
set @AOIPolygon = geography::STPolyFromText('POLYGON(('+@Coordinates+'))', 4326);


SELECT ID,Quad_Name,State from dbo.USCollared250K_Index 
WITH (INDEX(geom_sidx)) WHERE
@AOIPolygon.STIntersects(geom) = 1;
END


Note:
@Coordinates - comma separated pairs of coordinates like
eg. -104.864472 39.764004,-104.864472 39.853945,-105.057976 39.853945,
-105.057976 39.764004,-104.864472 39.764004