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

Wednesday, May 1, 2013

CRM 2011 JScript Syntaxes

XRM Page Model.

The Xrm.Page object serves as a namespace object to consolidate three properties on the form:

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.

Xrm.Page.data.entity

Xrm.Page.data provides an entity object that provides collections and methods to manage data within the entity form.

Xrm.Page.ui
Xrm.Page.ui provides collections and methods to manage the user interface of the form.




CRM Enity Properties
  •  Xrm.Page.data.entity.getEntityName()   //Entity Name
  •  Xrm.Page.data.entity.getId()                     //Record GUID
  •  Xrm.Page.ui.getFormType()                      //CRM Form Type (Integer)
    **Create (1), Update (2), Read Only (3), Disabled (4), Bulk Edit (6)
Get & Set Text Field
  • Xrm.Page.data.entity.attributes.get(“fld_name”).getValue()
  • Xrm.Page.data.entity.attributes.get(“fld_name”).setValue(“First”)
Get Lookup
  •      Xrm.Page.data.entity.attributes.get(“primarycontactid”)
  •     Xrm.Page.data.entity.attributes.get(“primarycontactid”).getValue()[0].id
  •     Xrm.Page.data.entity.attributes.get(“primarycontactid”).getValue()[0].name
Set Lookup
  •  var lookUpValue = new Array();
    lookUpValue[0] = new Object();
    lookUpValue[0].id = idValue;
    lookUpValue[0].name = textValue;
    lookUpValue[0].entityType = ‘{Entity_Name}’;
  • Xrm.Page.getAttribute(“primarycontactid”).setValue(lookUpValue);
Option Set Properties
  •  Xrm.Page.data.entity.attributes.get(“new_country”)
  • Xrm.Page.data.entity.attributes.get(“new_country”).getOptions()   // All Options
  •  Xrm.Page.data.entity.attributes.get(“new_country”).getText()         // Option Label value
  •  Xrm.Page.data.entity.attributes.get(“new_country”).getValue()       // Selected option value
Hide/Show controls
  • Xrm.Page.ui.controls.get(“name”).setVisible(true/false)
Disable/Enable controls
  •  Xrm.Page.ui.controls.get(“name”).setDisabled(true/false)
Set Focus
  • Xrm.Page.ui.controls.get(“name”).setFocus();
Set field’s Requirement Level
  • Xrm.Page.getAttribute(“name”).setRequiredLevel(“none”);
  • Xrm.Page.getAttribute(“name”).setRequiredLevel(“required”);
  •  Xrm.Page.getAttribute(“name”).setRequiredLevel(“recommended”);
Set the label for the control
  •  Xrm.Page.ui.controls.get(“name”).setLabel(“Label Text”);
Set URL for IFrams/WebResource
  •  Xrm.Page.ui.controls.get(“IFrame/WebResource Name”).setSrc(“URL”);
Get Parent of current control
  •  Xrm.Page.ui.controls.get(“name”).getParent();
“Current User” & “Organization” details
  • Xrm.Page.context.getUserId()                     //Current User ID
  •  Xrm.Page.context.getOrgUniqueName() //Organization Name
  •  Xrm.Page.context.getServerUrl()              //Server URL
  •  Xrm.Page.context.getUserRoles()             //Role ID’s of current user
Check isDirty
  • Xrm.Page.data.entity.getIsDirty()  // Form is IsDirty
  • Xrm.Page.data.entity.attributes.get(“new_name”).getIsDirty()  //Field is IsDirty
Save Form
  • function save(){Xrm.Page.data.entity.save();}
Save&close Form
  • function saveandclose(){Xrm.Page.data.entity.save(“saveandclose”);}
Close Form
  • function close(){Xrm.Page.ui.close();}
Expand/Collapse Tabs
  • var myTab = Xrm.Page.ui.tabs.get(“{tab_name}”);
  • myTab.setDisplayState(“expanded”); // To expand tab
  • myTab.setDisplayState(“collapsed”); // To collapse tab
Hide/Show Tabs & Sections
  • var myTab = Xrm.Page.ui.tabs.get(“{tab_name}”);
  • myTab.setVisible(True/False);
  • var mySec = myTab.sections.get(“{sec_name}”);
  • mySec.setVisible(True/False);