class Program
{
static IOrganizationService service;
static void Main(string[] args)
{
Console.WriteLine("Started");
Console.WriteLine(DateTime.Now.ToLocalTime());
Program app = new Program();
app.Run();
Console.WriteLine(DateTime.Now.ToLocalTime());
Console.WriteLine("Completed");
Console.ReadKey();
}
public void Run()
{
try
{
string OrgServiceUri = ConfigurationManager.AppSettings["OrgServiceUri"];
string UserName = ConfigurationManager.AppSettings["UserName"];
string Password = ConfigurationManager.AppSettings["Password"];
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(OrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
service = (IOrganizationService)proxy;
QueryExpression queryUser = new QueryExpression { EntityName = "systemuser" };
queryUser.Criteria.AddCondition("isdisabled", ConditionOperator.Equal, false);
queryUser.ColumnSet = new ColumnSet("systemuserid", "windowsliveid", "isdisabled", "fullname", "createdon", "modifiedon", "createdby", "domainname", "internalemailaddress", "caltype");
EntityCollection userCollection = service.RetrieveMultiple(queryUser);
Console.WriteLine("Total Enabled Users: {0}", userCollection.Entities.Count);
CreateLog("CreatedOn , ModifiedOn , CreatedBy , DomainName , Email , LicenseType , FullName , UserName , LastLogin");
foreach (var e in userCollection.Entities)
{
// Console.WriteLine("Processing: {0}", e["windowsliveid"]);
string Email = string.Empty;
string DomainName = string.Empty;
string FullName = string.Empty;
string userName = string.Empty;
DateTime Create = DateTime.MinValue;
string CreatedOn = string.Empty;
DateTime Modified = DateTime.MinValue;
string ModifiedOn = string.Empty;
EntityReference Created = null;
string CreatedBy = string.Empty;
OptionSetValue License = null;
string LicenseType = string.Empty;
if (e.Attributes.Contains("fullname"))
{
FullName = (string)e.Attributes["fullname"];
}
if (e.Attributes.Contains("windowsliveid"))
{
userName = (string)e.Attributes["windowsliveid"];
}
if (e.Attributes.Contains("createdon"))
{
Create = (DateTime)e.Attributes["createdon"];
CreatedOn = Create.ToString("dd/MM/yyyy");
}
if (e.Attributes.Contains("modifiedon"))
{
Modified = (DateTime)e.Attributes["modifiedon"];
ModifiedOn = Modified.ToString("dd/MM/yyyy");
}
if (e.Attributes.Contains("createdby"))
{
Created = (EntityReference)e.Attributes["createdby"];
CreatedBy = Created.Name;
}
if (e.Attributes.Contains("domainname"))
{
DomainName = (string)e.Attributes["domainname"];
}
if (e.Attributes.Contains("internalemailaddress"))
{
Email = (string)e.Attributes["internalemailaddress"];
}
if (e.Attributes.Contains("caltype"))
{
License = e.Attributes["caltype"] as OptionSetValue;
LicenseType = GetoptionsetText("systemuser", "caltype", License.Value, service);
}
string fetchXml = string.Format(@"<fetch distinct='true' no-lock='false' mapping='logical' count='1'>
<entity name='audit'>
<attribute name='createdon' />
<attribute name='userid' />
<attribute name='action' />
<order attribute='createdon' descending='true' />
<filter type='and'>
<condition attribute='action' operator='eq' value='64'/>
</filter>
<link-entity name='systemuser' from='systemuserid' to='objectid' link-type='inner' alias='SystemUser'>
<attribute name='systemuserid'/>
<filter type='and'>
<condition attribute='systemuserid' operator='eq' uitype='systemuser' value='{0}' />
</filter>
</link-entity>
</entity>
</fetch>", e.Id.ToString());
// Excute the fetch query and get the xml result.
RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml)
};
EntityCollection returnCollection = ((RetrieveMultipleResponse)service.Execute(fetchRequest1)).EntityCollection;
// System.Console.WriteLine(returnCollection.Entities.Count());
if (returnCollection.Entities.Count > 0)
{
foreach (var c in returnCollection.Entities)
{
DateTime Logon = DateTime.MinValue;
string Login = string.Empty;
if (c.Attributes.Contains("createdon"))
{
Logon = (DateTime)c.Attributes["createdon"];
Login = Logon.ToString("dd/MM/yyyy");
}
CreateLog(CreatedOn + "," + ModifiedOn + "," + CreatedBy + "," + DomainName + "," + Email + "," + LicenseType + "," + FullName + "," + userName + "," + Login);
Console.WriteLine(FullName + "," + userName + "," + Login);
}
}
else
{
CreateLog(CreatedOn + "," + ModifiedOn + "," + CreatedBy + "," + DomainName + "," + Email + "," + LicenseType + "," + FullName + "," + userName + ", Never Accessed");
Console.WriteLine(userName + ", Never Accessed");
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR2," + ex.Message + ex.InnerException);
CreateLog(ex.Message);
}
}
//This method will write log file for operations
public static void CreateLog(string logText)
{
StreamWriter log;
string date1 = DateTime.Now.ToShortDateString();
string today = date1.Replace("/", "_") + ".txt";
if (!System.IO.File.Exists(@"C:\Temp\UserAccess" + today))
{
log = new StreamWriter(@"C:\Temp\UserAccess" + today);
}
else
{
log = System.IO.File.AppendText(@"C:\Temp\UserAccess" + today);
}
log.WriteLine(logText);
log.Close();
}
public static string GetoptionsetText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)
{
string AttributeName = attributeName;
string EntityLogicalName = entityName;
RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = EntityLogicalName
};
RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
//IList<OptionMetadata> OptionsList = (from o in options.Options
// where o.Value.Value == optionSetValue
// select o).ToList();
//string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
string optionsetLabel = (from o in options.Options
where o.Value.Value == optionSetValue
select o).First().Label.UserLocalizedLabel.Label;
return optionsetLabel;
}
}