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");
}
}

}