Thursday, January 23, 2014

JavaScript references in Microsoft Dynamics CRM 2013

CRM 2013 fully supports the JavaScript object model from the previous version; however, it does not support the JavaScript object model from Microsoft Dynamics CRM 4.0.
Check out following reference documentation for client-side events and object models that can be used with JavaScript libraries. * marked is new in CRM 2013.
Xrm.Utility: Xrm.Utility object provides a container for useful functions not directly related to the current page. The following table lists the functions of Xrm.Utility.
Xrm.Utility
alertDialog
Displays   a dialog box with a message.
confirmDialog
Displays   a confirmation dialog box that contains a message as well as OK and Cancel   buttons.
isActivityType
Determine   if an entity is an activity entity.
openEntityForm
Opens   an entity form.
openWebResource
Opens   an HTML web resource.

Xrm.Page.data: Xrm.Page.data provides an entity object that provides collections and methods to manage data within the entity form. The following tables lists the functions of Xrm.Page.data and Xrm.Page.data.entity
Xrm.Page.data
getIsValid*
Do a validation check for the data in   the form.
refresh*
Asynchronously refresh all the data of the form without reloading the page.
save*
Saves the record asynchronously with the option to set callback functions.
Xrm.Page.data.entity
addOnSave
Adds a function to be called when the record is saved.
getDataXml
Returns a string representing the xml that will be sent to the server when the record is saved.
getEntityName
Returns a string representing the  logical name of the entity for the record.
getId
Returns a string representing the GUID   id value for the record.
getIsDirty
Returns a Boolean value that indicates if any fields in the form have been modified.
getPrimaryAttributeValue*
Gets a string for the value of the primary attribute of the entity.
removeOnSave
Removes a function to be called when the record is saved.
save
Saves the record with the options to close or new.

Xrm.Page.context: Xrm.Page.context provides methods to retrieve information specific to an organization, a user, or parameters that were passed to the form in a query string. The following table lists the functions of Xrm.Page.context.
 Xrm.Page.context
client.getClient*
Returns a value to indicate which client the script is executing in.
client.getClientState*
Returns a value to indicate the state of the client.
getClientUrl
Returns the base URL that was used to access the application.
getCurrentTheme
Returns a string representing the current Microsoft Office Outlook theme chosen by the user.
getOrgLcid
Returns the LCID value that represents   the base language for the organization.
getOrgUniqueName
Returns the unique text value of the   organization’s name.
getQueryStringParameters
Returns a dictionary object of key   value pairs that represent the query string arguments that were passed to the   page.
getUserId
Returns the GUID of the SystemUser.Id value for the current user.
getUserLcid
Returns the LCID value that represents the provisioned language that the user selected as their preferred language.
getUserName*
Returns the name of the current user.
getUserRoles
Returns an array of strings that represent the GUID values of each of the security roles that the user is  associated with.
isOutlookClient
(Deprecated) Returns a Boolean value indicating if the user is using Microsoft Dynamics CRM for Outlook.
isOutlookOnline
(Deprecated) Returns a Boolean value that indicates whether   the user is connected to the CRM server.
prependOrgName
Prepends the organization name to the   specified path.
Xrm.Page.ui:  Xrm.Page.ui provides collections and methods to manage the user interface of the form. The following table lists the functions of Xrm.Page.ui
Xrm.Page.ui
clearFormNotification*
Remove form level notifications.
close
Method to close the form.
formSelector.getCurrentItem
Method to return a reference to the   form currently being shown.
formSelector.items
A collection of all the form items accessible to the current user.
getViewPortHeight
Method to get the height of the viewport in pixels.
getViewPortWidth
Method to get the width of the viewport   in pixels.
getCurrentControl
Get the control object that currently has focus.
getFormType
Get the form context for the record.
navigation.items
A collection of all the navigation items on the page.
setFormNotification*
Display form level notifications.
refreshRibbon
Re-evaluate the ribbon data that controls what is displayed in it.
 Collections
Xrm.Page.data.entity.attributes
All attributes on the page.
Xrm.Page.ui.controls
All controls on the page.
Xrm.Page.ui.formSelector.items
All the forms available to the user.
Xrm.Page.ui.navigation.items
All the items in the form navigation   area.
Xrm.Page.ui.tabs
All the tabs on the page.
Xrm.Page Attribute.controls
All the controls for the attribute.
Xrm.Page.ui Section.controls
All the controls in the section.
Xrm.Page.ui Tab.sections
All the sections in the tab.
 Collections Methods
forEach
Apply an action in a delegate function to each object in the collection.
get
Get one or more object from the collection depending on the arguments passed.
getLength
Get the number of items in the collection.

Attributes: Attributes store the data available in the record. Attributes are available from the Xrm.Page.data.entity.attributes collection. To access an attribute you can use the Xrm.Page.data.entity.attributes.get method or the shortcut version Xrm.Page.getAttribute. Following table shows how you can query attribute properties to understand what kind of attribute it is or change the behavior of the attribute.
 Xrm.Page.getAttribute(“…”)
getAttributeType
Get the type of attribute.
getFormat
Get the attribute format.
getIsDirty
Determine whether the value of an   attribute has changed since it was last saved.
getIsPartyList
Determine whether a lookup attribute   represents a partylist lookup.
getMaxLength
Get the maximum length of string which   an attribute that stores string data can have.
getName
Get the name of the attribute.
getParent
Get a reference to the Xrm.Page.data.entity object that is the parent to all attributes.
getRequiredLevel
Returns a string value indicating   whether a value for the attribute is required or recommended.
getSubmitMode
Sets whether data from the attribute   will be submitted when the record is saved. always / never / dirty
getUserPrivilege
Determine what privileges a user has   for fields using Field Level Security.
getValue / setValue
Gets or Sets the data value for an   attribute.
setRequiredLevel
Sets whether data is required or   recommended for the attribute before the record can be saved. none / required  / recommended
setSubmitMode
Returns a string indicating when data   from the attribute will be submitted when the record is saved.
Number Attribute Methods
getMax / getMin
Returns a number indicating the maximum   or minimum allowed value for an attribute.
getPrecision
Returns the number of digits allowed to   the right of the decimal point.
setPrecision*
Override the precision set for a number attribute.
DateTime Attribute Methods
setIsAllDay*
Specify whether a date control should  set a value including the entire day.
setShowTime*
Specify whether a date control should  show the time portion of the date.
Controls: Controls represent the user interface elements in the form. Each attribute in the form will have at least one control associated with it. Not every control is associated with an attribute. IFRAME, web resource, and subgrids are controls that do not have attributes. Controls are available from the Xrm.Page.ui.controls collection. To access a control you can use the Xrm.Page.ui.controls.get method or the shortcut version Xrm.Page.getControl. The following table lists the functions of Controls.
Xrm.Page.getControl(“…”)  
clearNotification*
Remove a message already displayed for   a control.
getAttribute
Get the attribute that the control is   bound to.
getControlType
Get information about the type of   control.
getDisabled / setDisabled
Get or Set whether the control is   disabled.
getLabel / setLabel
Get or Set the label for the control.
getName
Get the name of the control.
getParent
Get the section object that the control   is in.
getVisible / setVisible
Get or Set a value that indicates   whether the control is currently visible.
setFocus
Sets the focus on the control.
setNotification*
Display a message near the control to   indicate that data is not valid.

Lookup Controls: The following table lists the functions of Lookup Control.
addCustomFilter*
Use fetchXml to add additional filters   to the results displayed in the lookup. Each filter will be combined with an   ‘AND’ condition.
addCustomView
Adds a new view for the lookup dialog   box.
addPreSearch*
Use this method to apply changes to   lookups based on values current just as the user is about to view results for   the lookup.
getDefaultView / setDefaultView
Get or Set Id value of the default   lookup dialog view.
removePreSearch*
Use this method to remove event handler

OptionSet: The following table lists the functions of OptionSet Control.
getInitialValue
Returns a value that represents the   value set for an optionset or boolean when the form opened.
getOption[s]
Returns an option object with the value   matching the argument passed to the method.
getSelectedOption
Returns the option object that is selected.
getText
Returns a string value of the text for   the currently selected option for an optionset attribute.
adoption / removeOption
Adds or remove an option to an option   set control.
clearOptions
Clears all options from an Option Set   control.

IFRAME and Web Resource Controls:  An IFRAME control allows you to include a page within a form by providing a URL. An HTML web resource added to a form is presented using an IFRAME element. Silverlight and image web resources are embedded directly within the page. The following table lists the functions of IFrame or Web Resource controls.
getData / setData
Get or Set the value of the data query   string parameter passed to a Silverlight web resource.
getInitialUrl
Returns the default URL that an I-frame   control is configured to display. This method is not available for web   resources.
getObject
Returns the object in the form that   represents an I-frame or web resource.
getSrc / setSrc
Get or Set the current URL being   displayed in an IFrame or web resource.

Sub-Grid Control: Sub-Grid control has refresh method. We can use this method to refresh data displayed in a Sub-Grid.
refresh
Refreshes the data displayed in a Sub-Grid.

OnChange Event: There are three methods you can use to work with the OnChange event for an attribute.
addOnChange / removeOnChange
Sets or remove a function to be called   when the attribute value is changed.
fireOnChange
Causes the OnChange event

Friday, October 18, 2013

Lambda Expressions with JOIN in C#

Let us consider that we have two tables 
1.Login[Username,Password,ID as fields] and 
2.Salary[ID,Salary as Fields]

Open MS Visual Studio--> select ASP.Net empty website
Add--> 2 Gridviews and 1 Button
Add--> Linq to SQL from Data and give the name as TestOpportunity
Add the SQL Connection and then Drag and Drop the Tables[Login and Salary]

write the below code on Button1_click
TestOpportunityDataContext TODC = new TestOpportunityDataContext();
//var jointables = TODC.logins.Where(r=>r.ID>=3).Select(r => new {r.username,r.password,r.ID }).Where(r=>r.username.Contains("Sai"));
var  result= TODC.logins.Select(r => new { r.username, r.password, r.ID }).Where(r => r.username.Contains("Sai")).Distinct();
GridView1.DataSource = result;
GridView1.DataBind();

var jointables= TODC.logins.Join(TODC.Salaries, b => b.ID, c => c.ID, (b, c) => new { b.username,b.password,c.Salary1});
GridView2.DataSource = jointables;
GridView2.DataBind();

Friday, September 13, 2013

Assembly {0} does not contain a Web resource with name {0}

Assembly 'ABC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' contains a Web resource with name 'PasswordExtenderBehavior.js', but does not contain an embedded resource with name 'PasswordExtenderBehavior.js'.
for this we need to select "PasswordExtenderBehavior.js" right click and go to properties select BUILD Action-> Embedded Resource 

Friday, September 6, 2013

Open MS CRM Form in Classic Mode always

Add the below code in Ribbon button. Whenever you click on that button the form will open in Classic Mode

function openClassicForm() {
 var name =Xrm.Page.data.entity.getEntityName();
 var id =Xrm.Page.data.entity.getId();
  var clientUrl = Xrm.Page.context.getClientUrl();
  var url = clientUrl + "/main.aspx?etn=" + name + "&extraqs=%3fid%3d" + id + "%26&pagetype=entityrecord&rof=true";
  parent.parent.window.open(url);
}

Monday, September 2, 2013

Check the Username and Password from Active Directory

using System.DirectoryServices.Protocols;[Add this reference]

namespace Usernamepassword
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
              LdapConnection connection = new LdapConnection("domain.com");
              //Ex:Gmail.com
              NetworkCredential credential = new NetworkCredential("username", "Password");
                connection.Credential = credential;
                connection.Bind();
                Console.WriteLine("Succesfully Logged In");
                Console.ReadKey();
            }
            catch (LdapException msg)
            {
                String error = msg.ServerErrorMessage;
                Console.WriteLine(msg);
                Console.ReadKey();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
                Console.ReadKey();
            }
        }
    }
}

Wednesday, August 28, 2013

Convert .mdb to SQL database

There's also the SQL Server Import and Export Wizard 
  1. Open SSMS.
  2. Create a new empty database.
  3. Right-click the database in the Object Explorer.
  4. Select Tasks | Import Data... from the context menu.
  5. Change the data source to Microsoft Access.
  6. Browse for the file name.
  7. Click Next...
  8. That's it :-)

Tuesday, August 27, 2013

Create a Trigger

Create a trigger that will insert the old and new Passwords into a Table.
Open SSMS--Select database[Master]-->Select tablename[Logins]-->Expand the table--> you can find the Triggers-->select that and right click to create New Trigger--> change the trigger as we need
In this example below am showing how can we store/insert the Password into Audit table[Old/New].
Audit is the new table with columns[OldPassword,NewPassword,DateTime].
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,K.Sai Krishna Yadav>
-- =============================================
CREATE TRIGGER AuditInfo 
   ON  Login
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
declare @OldValue Varchar(50)
declare @NewValue Varchar(50)
select @OldValue=password from deleted
select @NewValue=password from inserted
Insert into Audit(AuditInfo,OldValue,NewValue) values (GETDATE(),@OldValue,@NewValue)
SET NOCOUNT ON;
    -- Insert statements for trigger here
END
GO
The above Trigger will fire when an INSERT,DELETE,UPDATE happens on Logins Table.

Friday, August 9, 2013

Query to update multiple rows with particular data/string in SQL

update tablename set columnname=REPLACE(tablename.columnname,'string to search','string to replace')

Consider the below table with name 'Employee'
ID Name
1 sa
2 sa krishna
3 sa kumar
4 sa ganesh

After executing the update statement
update Employee set Name=REPLACE(Employee.Name,'sa','sai')  
then the final result will be
ID Name
1 sai
2 sai krishna
3 sai kumar
4 sai ganesh

Monday, July 22, 2013

Send Email to multiple receipts individually.

SmtpClient smtpclient = new SmtpClient();
            System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();
            MailAddress mailAddress = new MailAddress("EMailID", "Admin", 
System.Text.Encoding.UTF8);
            mailMsg.From = mailAddress;
            if (dtemail.Rows.Count > 0)
            {
                StringBuilder br = new StringBuilder();
                for (int i = 0; i < dtemail.Rows.Count; i++)
                {
                    string strTO = dtemail.Rows[i][0].ToString();
                    br.Append(dtemail.Rows[i][0].ToString()+";");
                }
                mailMsg.IsBodyHtml = true;
                mailMsg.Subject = Session["Subject"].ToString();
                mailMsg.Body = "<html><body><table><tr><td>" + Session["DecodeOriginal"] + "</td></tr></table></body></html>";
                smtpclient.Credentials = new System.Net.NetworkCredential("EMailID", "password");
                smtpclient.Host = "smtp.gmail.com";
                smtpclient.Port = 25;
                smtpclient.EnableSsl = true;
                string strtoaddress = br.ToString();
                string[] Addresses = strtoaddress.Split(';');
                foreach (string address in Addresses)
                {
                    if (address != "")
                    {
                        mailMsg.To.Add(new System.Net.Mail.MailAddress(address));
                        smtpclient.Send(mailMsg);
                        mailMsg.To.Clear();
                    }
                }
                Response.Write(@"<script language='javascript'>alert('Your Email has been sent successfully - Thank You.');</script>");
                btnSendMail.Visible = false;
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Please select Email-ID.');</script>");
            }

Monday, July 15, 2013

Plugin for SetState Message

In MS CRM 2011 we have  a  common requirement  for plugins setstate message i.e  when the  status  of  a  record changes (like activate/deactivated change of a  record etc.)
 So, here we  will look at some  plugin codes which executes to  update certain field when a record state changes ie activated/deactivated.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;

namespace SetState
{
   public class SetState:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));        
            try
            {
                if (context.InputParameters.Contains("EntityMoniker") )
                {
                    // Work with the Moniker
                    var targetEntity = (EntityReference)context.InputParameters["EntityMoniker"];
                    if (targetEntity.LogicalName != "new_activeacc")
                    { return; }
                    IOrganizationService service = factory.CreateOrganizationService(context.UserId);
                    Entity ac = service.Retrieve("new_activeacc", context.PrimaryEntityId, new ColumnSet(true));
                    ac.Attributes["new_checkamt"] = 0;
                    service.Update(ac);
                }
            }
            catch(Exception e)
            {
                throw new InvalidPluginExecutionException("An error occured for SetState plugin "+e.Message + e.InnerException);
            }            
          }
    }
}

Till now, the plugin code is perfect.
But we need to take some points into consideration while registering the plugin for setstate message

For the  above plugin to work we need to register the plugin for  both setstate and setstatedynamic message.
The reason why both messages are required is both messages perform the same action in CRM and  as there is no typical thumbrule  for which action setstate/setstatedynamic  mesage is  fired,its better to register the plugin for  both messages  so that  our plugin works properly.

Another Example
Here is a sample plugin that would prevent an inactive contact record from getting activated.

Plugin has been registered against contact entity and two steps have been registered one on setstate and other on setstatedynamicentity messages on Pre event.
public void Execute(IPluginExecutionContext context)
{
// In case of SetState and SetStateDynamicEntity message InputParameter
// would contain EntityMoniker parameter 
Moniker entity = null;
if (context.InputParameters.Properties.Contains("EntityMoniker") &&
context.InputParameters.Properties["EntityMoniker"] is Moniker)
{
entity = (Moniker)context.InputParameters.Properties["EntityMoniker"];
// Get the state to which record is to be changed
// If Active the record is being activated 
// If Inactive the record is being deactivated
string  state=
(string)context.InputParameters.Properties[ParameterName.State];
// Verify that the entity represents an account.
if (entity.Name == EntityName.contact.ToString() && state=="Active")
{
    throw new InvalidPluginExecutionException("Record can't be activated");
}
}

}

Thursday, June 20, 2013

Transfer data from one database to another database using scripts

Option 1 
Right click on the database you want to copy
Choose 'Tasks' > 'Generate scripts'
'Select specific database objects'
Check 'Tables' 
Mark 'Save to new query window'
Click 'Advanced'
Set 'Types of data to script' to 'Schema and data' 
Next, Next
You can now run the generated query on the new database.

Option 2
Right click on the database you want to copy
'Tasks' > 'Export Data'
Next, Next
Choose the database to copy the tables to
Mark 'Copy data from one or more tables or views'
Choose the tables you want to copy
Finish

To copy the Schema:
Right click on the database you want to copy
Choose 'Tasks' > 'Generate scripts'
'Select specific database objects' click Next,Next....

Wednesday, June 12, 2013

To find your PF Balance just click the below link

http://members.epfoservices.in/

JSON

Characterstics of JSON
Easy to read and write JSON.
Lightweight text based interchange format
Language independent.

Uses of JSON
It is used when writing JavaScript based application which includes browser extension and websites.
JSON format is used for serializing & transmitting structured data over network connection.
This is primarily used to transmit data between server and web application.
Web Services and API.s use JSON format to provide public data.
It can be used with modern programming languages.

JSON supports following two data structures:
Collection of name/value pairs: This Data Structure is supported by different programming language.
Ordered list of values: It includes array, list, vector or sequence etc.
There are following datatypes supported by JSON format:
Type Description
Number double- precision floating-point format in JavaScript
String double-quoted Unicode with backslash escaping
Boolean true or false
Array an ordered sequence of values
Value it can be a string, a number, true or false, null etc
Object an unordered collection of key:value pairs
Whitespace can be used between any pair of tokens
null empty
Simple Example in JSON
Example shows Books information stored using JSON considering language of books and there editions:
{
    "book": [
    {
       "id":"02",
       "language": "CRM",
       "edition": "4.0",
       "author": "Sai Krishna"
    },
    {
       "id":"05",
       "language": "CRM",
       "edition": "2011"
       "author": "Sai"
    }]
}

What is jQuery?

jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)

Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
$('*'): This selector selects all elements in the document.
$("p > *"): This selector selects all elements that are children of a paragraph element.
$("#specialID"): This selector function gets the element with id="specialID".
$(".specialClass"): This selector gets all the elements that have the class of specialClass.
$("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
$("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
$("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.
$("ul li:first"): This selector gets only the first <li> element of the <ul>.
$("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.
$("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>
$("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
$("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
$("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.
$("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.
$(":empty"): Selects all elements that have no children.
$("p:empty"): Selects all elements matched by <p> that have no children.
$("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
$("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
$("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.
$("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.
$("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.
$("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar
$("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.
$("li:even"): Selects all elements matched by <li> that have an even index value.
$("tr:odd"): Selects all elements matched by <tr> that have an odd index value.
$("li:first"): Selects the first <li> element.
$("li:last"): Selects the last <li> element.
$("li:visible"): Selects all elements matched by <li> that are visible.
$("li:hidden"): Selects all elements matched by <li> that are hidden.
$(":radio"): Selects all radio buttons in the form.
$(":checked"): Selects all checked boxex in the form.
$(":input"): Selects only form elements (input, select, textarea, button).
$(":text"): Selects only text elements (input[type=text]).
$("li:eq(2)"): Selects the third <li> element
$("li:eq(4)"): Selects the fifth <li> element
$("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
$("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
$("li:gt(1)"): Selects all elements matched by <li> after the second one.
$("p:gt(2)"): Selects all elements matched by <p> after the third one.
$("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.
$("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.
$("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>
$("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.
$("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.
$(":parent"): Selects all elements that are the parent of another element, including text.
$("li:contains(second)"): Selects all elements matched by <li> that contain the text second.

Friday, June 7, 2013

Remove duplicates from DataSet in .Net

da.Fill(ds,"Details");
DataTable dt = ds.Tables["Name"];
RemoveDuplicateRows(dt, "Name"); // Here Name is Column name of table
gvDetails.DataSource = ds;
gvDetails.DataBind();

// This method is used to delete duplicate rows of table
public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();//hash table is used to store different types of data.It will take two parameters as input[Value and Name].
ArrayList duplicateList = new ArrayList();
foreach (DataRow dtRow in dTable.Rows)
{
if (hTable.Contains(dtRow[colName]))
duplicateList.Add(dtRow);
else
hTable.Add(dtRow[colName], string.Empty);
}
foreach (DataRow dtRow in duplicateList)
dTable.Rows.Remove(dtRow);
return dTable;
}

Maintain the state of Checkbox values in GridView

Write the below two methods[PageIndexChanging] to save the checkbox values in gridview when paging is set to true.
        private void SaveCheckedValues()
        {
            ArrayList userdetails = new ArrayList();
            int index = -1;
            foreach (GridViewRow gvrow in gvdetails.Rows)
            {
                index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
                bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;

                // Check in the Session
                if (Session["CHECKED_ITEMS"] != null)
                    userdetails = (ArrayList)Session["CHECKED_ITEMS"];
                if (result)
                {
                    if (!userdetails.Contains(index))
                        userdetails.Add(index);
                }
                else
                    userdetails.Remove(index);
            }
            if (userdetails != null && userdetails.Count > 0)
                Session["CHECKED_ITEMS"] = userdetails;
        }
        private void PopulateCheckedValues()
        {
            ArrayList userdetails = (ArrayList)Session["CHECKED_ITEMS"];
            if (userdetails != null && userdetails.Count > 0)
            {
                foreach (GridViewRow gvrow in gvdetails.Rows)
                {
                    int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
                    if (userdetails.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }

Thursday, June 6, 2013

To show the GridView with no rows/data

Add the below code before binding the data to GridView
 if (ds.Tables[0].Rows.Count == 0)
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            grdview.DataSource = ds;
            grdview.DataBind();
            int columncount = grdview.Rows[0].Cells.Count;
            grdview.Rows[0].Cells.Clear();
            grdview.Rows[0].Cells.Add(new TableCell());
            grdview.Rows[0].Cells[0].ColumnSpan = columncount;
            grdview.Rows[0].Cells[0].Text = "No Records Found";
        }
        else
        {
            grdview.DataSource = ds.Tables[0];
            grdview.DataBind();
        }

Friday, May 10, 2013

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

I'm trying to up load my site and I'm getting this error message:
    Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive.

<compilation debug="true" targetFramework="4.0">

The site works fine on my local pc but won't open when I loaded it to my host at tried to view it on line.

Registering the framework with IIS is what worked for me:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i
Type the above statement in command prompt