.NET Core 8.0 Program.cs
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\office1_CORE_API.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
n ////: By default it will false make true to ////
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": { "sqlconnstr": "Data
Source=databaseserver;Initial Catalog=[db];User ID=abcACCOUNT;Password=[pwd];TrustServerCertificate=True;Connection
Timeout=900;" },
" office1Value": {
"frommail": "dev@enviabc.com",
"bccmail": "support@enviabc.com",
"mailport": "25", // in
error check other ports: 25 or 465 or 587
"isrule": "1",
"encode1": "@$#W!N!",
"sqlconntimeout": "1800",
"serverpath": "\\\\dca-dev-sever\\",
"filePath": "\\\\dca-dev-server\\importantfiles\\",
"fileurl": "https://dca-dev-server/office1spm/#/files",
"assetUrl": "https://dca-dev-server/capital"
}
}
using
Microsoft.AspNetCore.Authentication.Negotiate;
using
Microsoft.Extensions.DependencyInjection.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy("p1",
policy =>
{
policy.WithOrigins("http://localhost:8080", "https://localhost:8080",
"http://localhost:8000", "https://localhost:8000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
//builder.Services.AddAuthorization(options => //enable when kestrel server, but Kestral not
works properly with Windows Authentication.
//{
//
options.FallbackPolicy = options.DefaultPolicy;
//});
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if
(app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseCors("p1");
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
*======= * *======= * *======= * *======= * *=======
* *======= * *======= * *======= *
public class MailSender : IMailSender
{
private static IConfiguration
_configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
public static async Task<string>
SendMail(string to, string cc, string
subject, string message)
{
string fromAdd
= _configuration["office1Value:frommail"];
string bccmail
= _configuration["office1Value:bccmail"];
string
mailport = _configuration["office1Value:mailport"];
string isrule
= _configuration["office1Value:isrule"];
if (isrule
== "1") ServicePointManager.SecurityProtocol
= (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
MimeMessage mm = new MimeMessage();
MailboxAddress from = new MailboxAddress("",
fromAdd);
mm.From.Add(from);
mm.Bcc.Add(new MailboxAddress("",
bccmail.Trim()));
//// Add
multiple 'To' addresses ////
foreach (var address
in to.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
if
(address.ToLower().EndsWith("@office1.com"))
mm.To.Add(new MailboxAddress("",
address.Trim()));
else
{
List<Users>
oUsr = GetUserDetails(address.Trim());
foreach (Users u in oUsr)
if (u.DisplayName == address ||
u.Email.ToLower() == address.ToLower() || u.UserName.ToLower().Replace("office1\\", "") ==
address.ToLower().Replace("office1\\", ""))
mm.To.Add(new MailboxAddress("",
u.Email.Trim()));
}
}
// //
Add multiple 'Cc' addresses ////
if (!string.IsNullOrWhiteSpace(cc))
foreach (var address
in cc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
if (address.ToLower().EndsWith("@office1.com"))
mm.To.Add(new MailboxAddress("",
address.Trim()));
else
{
List<Users>
oUsr = GetUserDetails(address.Trim());
foreach (Users u in oUsr)
if
(u.DisplayName == address || u.Email.ToLower() == address.ToLower() ||
u.UserName.ToLower().Replace("office1\\", "") ==
address.ToLower().Replace("office1\\", ""))
mm.Cc.Add(new MailboxAddress("",
u.Email.Trim()));
}
}
mm.Subject = subject;
mm.Body = new TextPart("html") { Text
= message };
//mm.Cc.ad
= message;
using (var client
= new SmtpClient())
{
//client.Connect("mailserver.office1.com",
Convert.ToInt32(mailport), false);
await
client.ConnectAsync("mailserver.office1.com", Convert.ToInt32(mailport),
false);
//client.AuthenticateAsync("",
"");
// Send
the email
//client.Send(mm);
await
client.SendAsync(mm);
//
Disconnect from the SMTP server
//client.Disconnect(true);
await
client.DisconnectAsync(true);
}
mm.Dispose();
return "success";
}
public static async Task<string>
SendMailCoreStd(string to, string cc, string
subject, string message)
{
string fromAdd
= _configuration["apaValue:frommail"];
string bccmail
= _configuration["Office1Value:bccmail"];
string
mailport = _configuration["Office1Value:mailport"];
string isrule
= _configuration["Office1Value:isrule"];
if (isrule
== "1") ServicePointManager.SecurityProtocol
= (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
MimeMessage mm = new MimeMessage();
MailboxAddress from = new MailboxAddress("",
fromAdd);
mm.From.Add(from);
mm.Bcc.Add(new MailboxAddress("",
bccmail.Trim()));
//// Add
multiple 'To' addresses ////
foreach (var address
in to.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
mm.To.Add(new MailboxAddress("",
address.Trim()));
// //
Add multiple 'Cc' addresses ////
if (!string.IsNullOrWhiteSpace(cc))
foreach (var address
in cc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
mm.Cc.Add(new MailboxAddress("",
address.Trim()));
mm.Subject = subject;
mm.Body = new TextPart("html") { Text
= message };
//mm.Cc.ad
= message;
using (var client
= new SmtpClient())
{
//client.Connect("mailserver.office1.com",
Convert.ToInt32(mailport), false);
await
client.ConnectAsync("mailserver.office1.com", Convert.ToInt32(mailport),
false);
//client.AuthenticateAsync("",
"");
// Send
the email
//client.Send(mm);
await client.SendAsync(mm);
//
Disconnect from the SMTP server
//client.Disconnect(true);
await
client.DisconnectAsync(true);
}
mm.Dispose();
return "success";
}
public string
SendMail1(string to, string cc, string
subject, string message)
{
ServicePointManager.SecurityProtocol
= (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
MimeMessage mm = new MimeMessage();
MailboxAddress from = new MailboxAddress("OFFICE1
DEV", "ai_dev@office1.com");
MailboxAddress toM = new MailboxAddress("", to);
mm.From.Add(from);
mm.To.Add(toM);
mm.Subject = subject;
mm.Body = new TextPart("plain") { Text
= message };
//mm.Cc.ad
= message;
using (var client
= new SmtpClient())
{
client.ConnectAsync("mailserver.office1.com", 25, false);
//client.AuthenticateAsync("",
"");
// Send
the email
client.SendAsync(mm);
//
Disconnect from the SMTP server
client.DisconnectAsync(true);
}
mm.Dispose();
return "success";
}
internal static List<Users>
GetUserDetails(string sKey)
{
sKey
= sKey.Contains("office1\\") ?
sKey.Replace("office1\\", "") :
sKey;
List<Users>
lstADUsers = new List<Users>();
try
{
string
DomainPath = "LDAP://DC=office1,DC=com";
DirectoryEntry
searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search
= new DirectorySearcher(searchRoot);
search.Filter = string.Format("(mail={0})", sKey);
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("usergroup");
search.PropertiesToLoad.Add("displayname");//first
name
search.PropertiesToLoad.Add("objectCategory");
search.PropertiesToLoad.Add("objectClass");
search.SizeLimit = 25;
SearchResult result;
SearchResultCollection
resultCol = search.FindAll();
if
(resultCol != null && resultCol.Count
< 1)
{
search.Filter = string.Format("(sAMAccountName={0})", sKey);
search.SizeLimit = 25;
result = null;
resultCol = null;
resultCol = search.FindAll();
}
if
(resultCol != null && resultCol.Count
< 1)
{
search.Filter = string.Format("(&(|(objectClass=user)(objectClass=group))(anr={0}))", sKey);
search.SizeLimit = 25;
result = null;
resultCol = null;
resultCol = search.FindAll();
}
if
(resultCol != null)
{
for (int counter
= 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString
= string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname")
&&
result.Properties.Contains("mail")
&&
result.Properties.Contains("displayname"))
{
Users
objSurveyUsers = new Users();
objSurveyUsers.Email =
(String)result.Properties["mail"][0];
objSurveyUsers.UserName
= (String)result.Properties["samaccountname"][0];
objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
if (Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("group"))
objSurveyUsers.UserType = "Group";
else if (Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("person"))
objSurveyUsers.UserType = "Person";
else
objSurveyUsers.UserType = "";
lstADUsers.Add(objSurveyUsers);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return
lstADUsers;
}
}
public class FileManage
{/// <summary>
/// GET files from folder on DRive
/// </summary>
public static List<string>
GetFiles(string path)
{
List<string> lst
= new List<string>();
DirectoryInfo d = new DirectoryInfo(path);
if
(!d.Exists)
System.IO.Directory.CreateDirectory(path);
FileInfo[] Files
= d.GetFiles();
foreach (FileInfo file in Files)
lst.Add(file.Name);
return lst;
}
/// <summary>
/// GET files from folder on DRive
/// </summary>
public static async Task<string>
SaveFiles(string path, IFormFile
postedFile)
{
try
{
//// Delete 2 days old files from temp folder ////
if
(path.EndsWith(Office1Const.TEMP_FOLDER_NAME)
&& System.IO.Directory.Exists(path))
{
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(-2))
fi.Delete();
}
}
////
Save file ////
bool exists
= System.IO.Directory.Exists(path);
if
(!exists)
System.IO.Directory.CreateDirectory(path);
//var
filePath = Path.GetTempFileName();
var
filePath = path + "\\" +
RemoveSpecialCharacters(postedFile.FileName.Trim());
if
(postedFile.Length > 0)
{
using (var stream
= new FileStream(filePath,
FileMode.Create))
{
await
postedFile.CopyToAsync(stream);
}
}
return
postedFile.FileName;
}
catch (Exception ex)
{
Helper.WriteToLog("OFFICE1_API", "Office1->TslSamApproval()", ex);
return
ex.Message;
}
}
/// <summary>
/// coping temporary folder to permanent
Allocation folder
/// </summary>
public static void
CopyFilesTempToPermanent(string curPath, string
destPath, string fileName)
{
try
{
System.IO.File.Copy(curPath + "/" +
fileName, destPath + "/" + fileName);
}
catch (Exception Ex)
{ throw Ex; }
}
public static string
RemoveSpecialCharacters(string str)
{
return Regex.Replace(str,
"[^a-zA-Z0-9_.]+", "_");
}
}
public class Helper
{
private static IConfiguration
_configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
private string enc = "@$#W";
private readonly IConfiguration _conf;
public Helper(IConfiguration
configuration)
{
_conf
= configuration;
}
public static bool
EnsureUserInADGroup(string groupName, string
userName)
{
bool
retValue = false;
try
{
userName = userName.Replace("office1\\", "");
PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
"office1Support");
UserPrincipal user = UserPrincipal.FindByIdentity(ctx,
userName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,
IdentityType.Name, groupName);
if (user
!= null && grp != null)
{
retValue = grp.GetMembers(true).Contains(user);
grp.Dispose();
}
}
catch (Exception)
{
retValue = false; }
return
retValue;
}
public static string
ConString()
{/*
OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();
builder.Driver = "{Simba Spark ODBC Driver}"; // Or the exact
name of your installed Databricks ODBC driver
builder.Add("Host", "adb-.2.azuredatabricks.net");//adb-260329400975751.11.azuredatabricks.net
builder.Add("Port", "443"); // Standard port for
HTTPS
builder.Add("ThriftTransport", "2");
builder.Add("AuthMech", "3"); // For Personal Access
Token authentication
builder.Add("UID", "token");
builder.Add("PWD", "dapi7b11e9fab06");//QA
token: dapi3d46de2ff318418ed318 dev
token: dapi7b11e9af06339fab06 for
builder.Add("HTTPPath", "sql/1.0/warehouses/7abfa322");//
/sql/1.0/warehouses/7a8fa2322
builder.Add("SSL", "1"); // Enable SSL/TLS
return builder.ConnectionString;
*/
OdbcConnectionStringBuilder builder
= new OdbcConnectionStringBuilder();
builder.Driver = "{Simba Spark ODBC Driver}"; // Or
the exact name of your installed Databricks ODBC driver
builder.Add("Host", "adb-.2.azuredatabricks.net");//adb-260329400975751.11.azuredatabricks.net
builder.Add("Port", "443"); //
Standard port for HTTPS
builder.Add("ThriftTransport", "2");
builder.Add("AuthMech", "3"); // For
Personal Access Token authentication
builder.Add("UID", "token");
builder.Add("PWD", "dapieafds21334");//QA
token: dapieafds21334dev token: dapieafds21334
for ashwini
builder.Add("HTTPPath", "/sql/1.0/warehouses/dapieafds21334");//
/sql/1.0/warehouses/7ab4f659f8fa2322
builder.Add("SSL", "1"); //
Enable SSL/TLS
return
builder.ConnectionString;
}
public DataSet
GetResultFromSQLDatabase(string cmdText, List<SqlParameter>
paramColl)
{
DataSet
dsResult = new DataSet();
string
configuration = _conf.GetConnectionString("sqlconnstr");
string pw =
_conf["Office1Value:encode1"];
pw =
pw.Replace(enc, "");
configuration = configuration.Replace("[pwd]", pw);
configuration = configuration.Replace("[db]", "IMDb");
using (SqlConnection
connection = new SqlConnection(configuration))
{
SqlDataAdapter
sqlAdapter;
SqlCommand
sqlCommand;
sqlCommand = new SqlCommand(cmdText,
connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
if (!string.IsNullOrEmpty(_conf["Office1Value:sqlconntimeout"]))
sqlCommand.CommandTimeout = Convert.ToInt32(_conf["Office1Value:sqlconntimeout"]);
foreach (SqlParameter p in
paramColl)
sqlCommand.Parameters.Add(p);
sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dsResult);
sqlAdapter.Dispose();
sqlCommand.Dispose();
}
return
dsResult;
}
public string
BulkCopyToTable(DataTable dtMasterData, string
TableName)
{
string
configuration = _conf.GetConnectionString("sqlconnstr");
string pw =
_conf["Office1Value:encode1"];
pw =
pw.Replace(enc, "");
configuration = configuration.Replace("[pwd]", pw);
configuration = configuration.Replace("[db]", "SPM");
using (SqlConnection
connection = new SqlConnection(configuration))
{
connection.Open();
SqlBulkCopy
bulkCopy = new SqlBulkCopy(connection);
bulkCopy.BulkCopyTimeout = 3000;
bulkCopy.DestinationTableName = TableName.ToUpper();
foreach (DataColumn column in
dtMasterData.Columns)
{
bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
}
bulkCopy.WriteToServer(dtMasterData);
connection.Close();
}
return "Data
Inserted Successfully.";
}
public static void
WriteToLog(string page, string method,
Exception ex)
{
List<SqlParameter>
sqlParam = new List<SqlParameter>();
SqlParameter p1 = new SqlParameter("@Page", SqlDbType.NVarChar);
p1.Value = page;
sqlParam.Add(p1);
SqlParameter p2 = new SqlParameter("@Method", SqlDbType.NVarChar);
p2.Value = method;
sqlParam.Add(p2);
SqlParameter p3 = new SqlParameter("@Message", SqlDbType.NVarChar);
p3.Value = ex.Message;
sqlParam.Add(p3);
SqlParameter p4 = new SqlParameter("@StackTrace", SqlDbType.NVarChar);
p4.Value = ex.StackTrace;
sqlParam.Add(p4);
GetResultFromSqlDatabase("[dbo].[usp_ExceptionLog]",
sqlParam, Office1Const.PART_VIEWER);
}
public static DataSet
GetResultFromSqlDatabase(string cmdText, List<SqlParameter>
paramColl, string dbName)
{
DataSet
dsResult = new DataSet();
string
configuration = _configuration.GetConnectionString("sqlconnstr");
string pw =
_configuration["Office1Value:encode1"];
pw =
pw.Replace("@$#W", "");
configuration = configuration.Replace("[pwd]", pw);
switch
(dbName)
{
case "IMDb":
configuration = configuration.Replace("[db]", "IMmmddd");
break;
case "PART_VIEWER":
configuration = configuration.Replace("[db]", "PARTSOFMACHINE");
break;
case "":
configuration = configuration.Replace("[db]", "");
break;
}
using (SqlConnection
connection = new SqlConnection(configuration))
{
SqlDataAdapter
sqlAdapter;
SqlCommand
sqlCommand;
sqlCommand = new SqlCommand(cmdText,
connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
if (!string.IsNullOrEmpty(_configuration["sqlconntimeout"]))
sqlCommand.CommandTimeout = Convert.ToInt32(_configuration["sqlconntimeout"]);
foreach (SqlParameter p in
paramColl)
sqlCommand.Parameters.Add(p);
sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dsResult);
sqlAdapter.Dispose();
sqlCommand.Dispose();
}
return
dsResult;
}
/// <summary>
/// common
method to converting datatable into XML
/// </summary>
public static string
ConvertDataTableToXML(DataTable oDataTable, string
DtKeyName)
{
StringBuilder sb = new StringBuilder();
sb.Append("<NewDataSet>");
for (int i = 0;
i < oDataTable.Rows.Count; i++)
{
if
(oDataTable.Columns.Count > 0)
{
sb.Append("<" + DtKeyName + "
");
for (int col =
0; col < oDataTable.Columns.Count; col++)
sb.Append(oDataTable.Columns[col].ColumnName.Replace("
", "") + "=\"" + Convert.ToString(oDataTable.Rows[i][col]).Replace("&", "&").Replace("\"", """) + "\"
");
sb.Append(" />");
}
}
sb.Append("</NewDataSet>");
return
sb.ToString();
}
public static string
EncodeBase64(string plainText)
{
var
plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string
DecodeBase64(string base64EncodedData)
{
var
base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return
System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string
GetAppConfigValue(string str)
{
return Convert.ToString(_configuration[str]);
}
}
public class Result
{
public string
IsSuccess { set; get; }
public string Message
{ set; get; } = string.Empty;
public int Valid {
get; set; }
}
public class ADAttribute
{
public static ADAttributes GetADAttibutes(string empID)
{
using (var context = new PrincipalContext(ContextType.Domain, Office1Const.OFFICE1))
{
var user = UserPrincipal.FindByIdentity(context, empID);
if (user != null)
{
//userProperties.EmpName =
user.Name;
DirectoryEntry sresult =
user.GetUnderlyingObject() as DirectoryEntry;
ADAttributes objAd = new
ADAttributes
{
employeeId =
sresult.Properties["employeeid"].Count > 0 ?
sresult.Properties["employeeid"][0].ToString() : string.Empty,
employeeType =
sresult.Properties["employeeType"].Count > 0 ?
sresult.Properties["employeeType"][0].ToString() : string.Empty,
sAMAccountName =
sresult.Properties["sAMAccountName"].Count > 0 ?
sresult.Properties["sAMAccountName"][0].ToString() : string.Empty,
department =
sresult.Properties["department"].Count > 0 ?
sresult.Properties["department"][0].ToString() : string.Empty,
departmentNumber =
sresult.Properties["departmentNumber"].Count > 0 ?
sresult.Properties["departmentNumber"][0].ToString() : string.Empty,
division =
sresult.Properties["division"].Count > 0 ?
sresult.Properties["division"][0].ToString() : string.Empty,
manager =
sresult.Properties["manager"].Count > 0 ?
sresult.Properties["manager"][0].ToString() : string.Empty,
managerSamAcnt =
(sresult.Properties.Contains("manager") == true) ?
Convert.ToString(sresult.Properties["manager"][0]).Split(',')[0].Split('=')[1]
: string.Empty, // Splitting manger name
displayName =
sresult.Properties["displayName"].Count > 0 ?
sresult.Properties["displayName"][0].ToString() : string.Empty,
PhysicalDeliveryOfficeName
= sresult.Properties["physicalDeliveryOfficeName"].Count > 0 ?
sresult.Properties["physicalDeliveryOfficeName"][0].ToString() :
string.Empty,
mail =
sresult.Properties["mail"].Count > 0 ?
sresult.Properties["mail"][0].ToString() : string.Empty,
memberOf =
sresult.Properties["memberOf"].Count > 0 ?
sresult.Properties["memberOf"][0].ToString() : string.Empty,
userAccountControl =
sresult.Properties["userAccountControl"].Count > 0 ?
sresult.Properties["userAccountControl"][0].ToString() :
string.Empty,
givenName =
sresult.Properties["givenName"].Count > 0 ?
sresult.Properties["givenName"][0].ToString() : string.Empty,
objectClass =
sresult.Properties["objectClass"].Count > 0 ?
sresult.Properties["objectClass"][0].ToString() : string.Empty,
postOfficeBox =
sresult.Properties["postOfficeBox"].Count > 0 ?
sresult.Properties["postOfficeBox"][0].ToString() : string.Empty,
telephoneNumber =
sresult.Properties["telephoneNumber"].Count > 0 ?
sresult.Properties["telephoneNumber"][0].ToString() : string.Empty,
uId =
sresult.Properties["uId"].Count > 0 ?
sresult.Properties["uId"][0].ToString() : string.Empty,
Location =
sresult.Properties["L"].Count > 0 ?
sresult.Properties["L"][0].ToString() : string.Empty,
Company =
sresult.Properties["Company"].Count > 0 ?
sresult.Properties["Company"][0].ToString() : string.Empty,
FirstName =
sresult.Properties["givenName"].Count > 0 ?
sresult.Properties["givenName"][0].ToString() : string.Empty,
LastName =
sresult.Properties["sn"].Count > 0 ?
sresult.Properties["sn"][0].ToString() : string.Empty,
co =
sresult.Properties["co"].Count > 0 ?
sresult.Properties["co"][0].ToString() : string.Empty
};
return objAd;
}
else
return new ADAttributes();
}
}
internal static List<Users> GetUserDetails(string sKey)
{
sKey = sKey.Contains("OFFICE1\\") ? sKey.Replace("OFFICE1\\",
"") : sKey;
List<Users> lstADUsers = new List<Users>();
try
{
string DomainPath = "LDAP://DC=OFFICE1,DC=com";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = string.Format("(mail={0})", sKey);
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("usergroup");
search.PropertiesToLoad.Add("displayname");//first name
search.PropertiesToLoad.Add("objectCategory");
search.PropertiesToLoad.Add("objectClass");
search.PropertiesToLoad.Add("thumbnailPhoto");
search.PropertiesToLoad.Add("manager");
search.SizeLimit = 25;
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter
< resultCol.Count; counter++)
{
string UserNameEmailString
= string.Empty;
result =
resultCol[counter];
if
(result.Properties.Contains("samaccountname") &&
result.Properties.Contains("mail") &&
result.Properties.Contains("displayname"))
{
Users objSurveyUsers =
new Users();
objSurveyUsers.Email =
(String)result.Properties["mail"][0];
objSurveyUsers.ManagerSamAcnt =
(result.Properties.Contains("manager") == true) ?
Convert.ToString(result.Properties["manager"][0]).Split(',')[0].Split('=')[1]
: string.Empty;
objSurveyUsers.UserName
= (String)result.Properties["samaccountname"][0];
objSurveyUsers.DisplayName =
(String)result.Properties["displayname"][0];
if
(result.Properties.Contains("thumbnailPhoto"))
objSurveyUsers.Thumbnail =
result.Properties["thumbnailPhoto"][0] as byte[];
if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("group"))
objSurveyUsers.UserType = "Group";
else if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("person"))
objSurveyUsers.UserType = "Person";
else
objSurveyUsers.UserType = "";
lstADUsers.Add(objSurveyUsers);
}
}
}
search.Filter = string.Format("(sAMAccountName={0})", sKey);
search.SizeLimit = 25;
//search.PropertiesToLoad.Add("*");
result = null;
resultCol = null;
resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter
< resultCol.Count; counter++)
{
string UserNameEmailString
= string.Empty;
result =
resultCol[counter];
if
(result.Properties.Contains("samaccountname") &&
result.Properties.Contains("mail") &&
result.Properties.Contains("displayname"))
{
Users objSurveyUsers =
new Users();
objSurveyUsers.Email =
(String)result.Properties["mail"][0];
objSurveyUsers.ManagerSamAcnt =
(result.Properties.Contains("manager") == true) ?
Convert.ToString(result.Properties["manager"][0]).Split(',')[0].Split('=')[1]
: string.Empty;
objSurveyUsers.UserName
= (String)result.Properties["samaccountname"][0];
objSurveyUsers.DisplayName =
(String)result.Properties["displayname"][0];
if
(result.Properties.Contains("thumbnailPhoto"))
objSurveyUsers.Thumbnail =
result.Properties["thumbnailPhoto"][0] as byte[];
if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("group"))
objSurveyUsers.UserType = "Group";
else if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("person"))
objSurveyUsers.UserType = "Person";
else
objSurveyUsers.UserType = "";
lstADUsers.Add(objSurveyUsers);
}
}
}
search.Filter =
string.Format("(&(objectClass=user)(givenname={0}*))", sKey);
;//string.Format("(&(objectClass=user)(givenname=ashwini))");//"(&(objectClass=user)(givenname=Ash*)(sn=A))";//"((sAMAccountName=))";
//(mail = ashwini_sharma@contractor.office1.com)// |(mail=mat.com)
search.SizeLimit = 25;
result = null;
resultCol = null;
resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter
< resultCol.Count; counter++)
{
string UserNameEmailString
= string.Empty;
result =
resultCol[counter];
if
(result.Properties.Contains("samaccountname") &&
result.Properties.Contains("mail") &&
result.Properties.Contains("displayname"))
{
Users objSurveyUsers =
new Users();
objSurveyUsers.Email =
(String)result.Properties["mail"][0];
objSurveyUsers.ManagerSamAcnt =
(result.Properties.Contains("manager") == true) ?
Convert.ToString(result.Properties["manager"][0]).Split(',')[0].Split('=')[1]
: string.Empty;
objSurveyUsers.UserName
= (String)result.Properties["samaccountname"][0];
objSurveyUsers.DisplayName =
(String)result.Properties["displayname"][0];
if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("group"))
objSurveyUsers.UserType = "Group";
else if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("person"))
objSurveyUsers.UserType = "Person";
else
objSurveyUsers.UserType = "";
lstADUsers.Add(objSurveyUsers);
}
}
}
}
catch (Exception ex)
{
Users objSurveyUsers = new Users();
objSurveyUsers.Email = "Error";
objSurveyUsers.UserName = "Error";
objSurveyUsers.DisplayName = ex.Message;
lstADUsers.Add(objSurveyUsers);
}
return lstADUsers;
}
public static IEnumerable<Users> GetPeoples(string sKey)
{
sKey = sKey.Contains("OFFICE1\\") ? sKey.Replace("OFFICE1\\",
"") : sKey;
List<Users> lstADUsers = new List<Users>();
try
{
string DomainPath = "LDAP://DC=OFFICE1,DC=com";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = string.Format("(mail={0})", sKey);
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("usergroup");
search.PropertiesToLoad.Add("displayname");//first name
search.PropertiesToLoad.Add("objectCategory");
search.PropertiesToLoad.Add("objectClass");
search.PropertiesToLoad.Add("manager");
search.SizeLimit = 25;
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
search.Filter =
string.Format("(&(|(objectClass=user)(objectClass=group))(anr={0}))",
sKey);
//search.Filter =
string.Format("(&(objectClass=user)(givenname={0}))", sKey);
//search.Filter = string.Format("(&(objectClass = user)(|
(displayName = *{0} *)(givenName = *{0} *)(sn = *{0} *)))", sKey);
search.SizeLimit = 25;
result = null;
resultCol = null;
resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter
< resultCol.Count; counter++)
{
string UserNameEmailString
= string.Empty;
result =
resultCol[counter];
if
(result.Properties.Contains("samaccountname") &&
result.Properties.Contains("mail") &&
result.Properties.Contains("displayname"))
{
Users objSurveyUsers =
new Users();
objSurveyUsers.Email =
(String)result.Properties["mail"][0];
objSurveyUsers.ManagerSamAcnt =
(result.Properties.Contains("manager") == true) ?
Convert.ToString(result.Properties["manager"][0]).Split(',')[0].Split('=')[1]
: string.Empty;
objSurveyUsers.UserName
= (String)result.Properties["samaccountname"][0];
objSurveyUsers.DisplayName =
(String)result.Properties["displayname"][0];
if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("group"))
objSurveyUsers.UserType = "Group";
else if
(Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("person"))
objSurveyUsers.UserType = "Person";
else
objSurveyUsers.UserType = "";
lstADUsers.Add(objSurveyUsers);
}
}
}
}
catch (Exception ex)
{
Users objSurveyUsers = new Users();
objSurveyUsers.Email = "Error";
objSurveyUsers.UserName = "Error";
objSurveyUsers.DisplayName = ex.Message;
lstADUsers.Add(objSurveyUsers);
}
return lstADUsers;
}
}
public class ADAttributes
{
public string
employeeId { get; set; }
public string
employeeType { get; set; }
public string mail { get; set; }
public string
sAMAccountName { get; set; }
public string
displayName { get; set; }
public string
givenName { get; set; }
public string manager
{ get; set; }
public string
memberOf { get; set; }
public string
department { get; set; }
public string
departmentNumber { get; set; }
public string
division { get; set; }
public string
userAccountControl { get; set; }
public string
telephoneNumber { get; set; }
public string
postOfficeBox { get; set; }
public string
PhysicalDeliveryOfficeName { get; set; }
public string
objectClass { get; set; }
public string uId { get; set; }
public string domain
{ get; set; }
public string
Location { get; set; }
public string Company
{ get; set; }
public string
FirstName { get; set; }
public string
LastName { get; set; }
public string
managerSamAcnt { get; set; }
public string
ManagerEmail { get; set; }
public string
ManagerLoginName { get; set; }
public string
ManagerDisplayName { get; set; }
public string
ManagerDomain { get; set; }
public string co { get; set; }
public string
ManagerEmployeeID { get; set; }
public string
ManagerPhoneNumber { get; set; }
}
public class Result
{
public string
IsSuccess { set; get; }
public string Message
{ set; get; } = string.Empty;
public int Valid {
get; set; }
}
public class Users
{
public string Email {
get; set; }
public string
UserName { get; set; }
public string
DisplayName { get; set; }
public string
UserType { get; set; }
public byte[]
Thumbnail { get; set; }
public string
ManagerSamAcnt { get; set; }
}
====================================================
Excel reading - by -- Microsoft default openxml package. -- - --- -
using
DocumentFormat.OpenXml.Packaging;
using
DocumentFormat.OpenXml.Spreadsheet;
using
Microsoft.AspNetCore.Http;
using System.Data;
namespace AM.ASHEET
{
public class ESheet
{
public static DataTable
ReadExcelToDTable(IFormFile file, int col)
{
DataTable dt = new DataTable();
using (SpreadsheetDocument
spreadsheetDocument = SpreadsheetDocument.Open(file.OpenReadStream(),
false))
{
WorkbookPart workbookPart =
spreadsheetDocument.WorkbookPart;
Sheet sheet =
workbookPart.Workbook.Descendants<Sheet>().First();
WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
SheetData sheetData =
worksheetPart.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
int icnt = 0;
foreach (Cell cell in
rows.ElementAt(0))
{
if (icnt < col)
dt.Columns.Add(GetCellValue(spreadsheetDocument, cell));
icnt++;
}
foreach (Row row in rows) //this
will also include your header row...
{
DataRow tempRow =
dt.NewRow();
for (int i = 0;
i < col; i++)
{
tempRow[i] =
GetCellValue(spreadsheetDocument, row.Descendants<Cell>().ElementAt(i));
}
dt.Rows.Add(tempRow);
}
}
dt.Rows.RemoveAt(0);
return dt;
}
public static string
GetCellValue(SpreadsheetDocument
document, Cell cell)
{
SharedStringTablePart
stringTablePart = document.WorkbookPart.SharedStringTablePart;
string value =
cell.CellValue.InnerXml;
if
(cell.DataType != null && cell.DataType.Value
== CellValues.SharedString)
{
return
stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
}
else
{
return value;
}
}
}
}
[Route("IProjUpload")]
public Result
InvProjAdminTslUpload(IFormFile file)
{
Result er = new Result();
try
{
if (file
!= null || file.Length > 0)
{
var
httpRequest = _iHttpContextAccessor.HttpContext.Request;
DataTable dt = new ESheet().ReadExcelToDTable(file,
5);
er.Message += "ash";
}
}
catch (Exception ex)
{
//Helper.WriteToLog("API",
" -> IProjUpload ()", ex);
er.IsSuccess = AConst.FAIL;
er.Message = ex.Message;
}
return er;
using
Microsoft.AspNetCore.Authentication.Negotiate;
using
Microsoft.Extensions.DependencyInjection.Extensions;
internal class Program
{
private static void Main(string[] args)
{
var builder
= WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("p1",
policy =>
{
policy.WithOrigins("http://localhost:8080",
"https://localhost:8080")
.AllowAnyHeader()
.AllowAnyMethod();
});
});// ash: for cors api and site access allowing
// Add
services to the container. //"https://dca-dev-997",
//windows
authentication
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
}); //ash: for windows authentication
//builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
//builder.Services.AddAuthorization(options
=>
//{
// // By default, all incoming requests will
be authorized according to the default policy.
// options.FallbackPolicy =
options.DefaultPolicy;
//});
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();//ash: for http context
builder.Services.AddControllers();
// Learn
more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app =
builder.Build();
//
Configure the HTTP request pipeline.
if
(app.Environment.IsDevelopment() || app.Environment.IsProduction()) //ash:swagger in prod
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseCors("p1"); //app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
//app.UseAuthentication(WindowsPrincipal);
app.MapControllers();
app.Run();
}
}
working on - : woring on today
using
Microsoft.AspNetCore.Authentication.Negotiate;
using
Microsoft.Extensions.DependencyInjection.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add
services to the container.
builder.Services.AddCors(options
=>
{
options.AddPolicy("p1",
policy =>
{
policy.WithOrigins("http://localhost:8080",
"https://localhost:8080")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
//builder.Services.AddCors(options
=>
//{
// options.AddDefaultPolicy(
// policy =>
// {
//
policy.WithOrigins("http://localhost:8080")
// .AllowAnyHeader()
// .AllowAnyMethod()
// .AllowCredentials();
// });
//});
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddAuthorization(options
=>
{
options.FallbackPolicy =
options.DefaultPolicy;
});
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddControllers();
// Learn
more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
//
Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment() ||
app.Environment.IsProduction())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("p1");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();