download ADLogin.aspx.cs
Language: C#
LOC: 346
Project Info
common-component-mng-sys - Common Componen...e ...(common-component-mng-sys)
Server: Google
Type: svn
...on‑component‑mng‑sys\trunk\
   AddNewComponent.aspx
   AddNewComponent.aspx.cs
   ADLogin.aspx
   ADLogin.aspx.cs
   ...SearchActionChoice.aspx
   ...rchActionChoice.aspx.cs
   CathayBkRSS.xml
   Comment.aspx
   Comment.aspx.cs
   ...n-component-mng-sys.sln
   ...onent-mng-sys_Model.tgs
   ComponentsList.html
   Default.aspx
   Default.aspx.cs
   Downloading.aspx
   Downloading.aspx.cs
   ErrorPage.htm
   Global.asax
   Logon.aspx
   Logon.aspx.cs
   ManagerMain.aspx
   ManagerMain.aspx.cs
   MasterPage.master
   MasterPage.master.cs
   ReviseComponent.aspx
   ReviseComponent.aspx.cs
   SearchComponent.aspx
   SearchComponent.aspx.cs
   SearchResult.aspx
   SearchResult.aspx.cs
   StatisticsReport.aspx
   StatisticsReport.aspx.cs
   ...oDownloadComponent.aspx
   ...wnloadComponent.aspx.cs
   web.config
   Web.sitemap
   ...ejectReasonAndMail.aspx
   ...ctReasonAndMail.aspx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

public partial class ADLogin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        DirectoryEntry dirEntry = GetDirectoryEntry();
        Style bodyStyle = new Style();
        bodyStyle.ForeColor = System.Drawing.Color.Black;
        bodyStyle.BackColor = System.Drawing.Color.Wheat;  //]wIC


        //N˦[JثeHeader
        Page.Header.StyleSheet.CreateStyleRule(bodyStyle, null, "BODY");

    }

//Setting up the connection
 public static DirectoryEntry GetDirectoryEntry()
 { 
   DirectoryEntry de = new DirectoryEntry();
   de.Path = "LDAP://OU=Domain,DC=Cathaybk,DC=com";  //AD
   de.AuthenticationType = AuthenticationTypes.Secure;

   return de;
}

   // Translate the friendly domain name to fully qualified domain:
public static string FriendlyDomainToLdapDomain(string friendlyDomainName)
{
    string ldapPath = null;
    try
    {
        DirectoryContext objContext = new DirectoryContext(
                            DirectoryContextType.Domain, friendlyDomainName);
        Domain objDomain = Domain.GetDomain(objContext);
        ldapPath = objDomain.Name;
    }
    catch (DirectoryServicesCOMException e)
    {
        ldapPath = e.Message.ToString();
    }
    return ldapPath;       
}


//Enumerate Domains in the Current Forest
public static ArrayList EnumerateDomains()
{
    ArrayList alDomains = new ArrayList();
    Forest currentForest = Forest.GetCurrentForest();
    DomainCollection myDomains = currentForest.Domains;
  
    foreach (Domain objDomain in myDomains)
        {
            alDomains.Add(objDomain.Name);
        }
    return alDomains;
}


//    Enumerate Objects in an OU
//The parameter OuDn is the Organizational Unit distinguishedName such as OU=Users,dc=myDomain,dc=com
 public ArrayList EnumerateOU(string OuDn)
{
  ArrayList alObjects = new ArrayList();
  try
    {
        DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + OuDn);
        foreach (DirectoryEntry child in directoryObject.Children)
        {
            string childPath = child.Path.ToString();
            alObjects.Add(childPath.Remove(0,7)); //remove the LDAP prefix from the path
            child.Close();
            child.Dispose();
        }
        directoryObject.Close();
        directoryObject.Dispose();
    }
    catch (DirectoryServicesCOMException e)
    {
        Console.WriteLine("An Error Occurred: " + e.Message.ToString());
    }
    return alObjects;
}        

//Check for the Existence of an Object
//This method does not need you to know the distinguishedName, you can concat strings or even guess a location and it will still run 
//  (and return false if not found).
public static bool Exists(string objectPath)
{
    bool found = false;
    if (DirectoryEntry.Exists("LDAP://" + objectPath))
    {
        found = true;
    }
    return found;
}


// Move an Object From One Location to Another
// It should be noted that the string newLocation should NOT include the CN= value of the object. 
// The method will pull that from the objectLocation string for you. So object CN=group,OU=GROUPS,DC=contoso,DC=com is sent in as the objectLocation but the newLocation is something like: OU=NewOUParent,DC=contoso,DC=com. The method will take care of the CN=group.

public void Move(string objectLocation, string newLocation)
{
  //For brevity, removed existence checks
   DirectoryEntry eLocation = new DirectoryEntry("LDAP://" + objectLocation);
   DirectoryEntry nLocation = new DirectoryEntry("LDAP://" + newLocation);
   string newName = eLocation.Name;
   eLocation.MoveTo(nLocation, newName);
   nLocation.Close();
   eLocation.Close();
}


// Enumerate Multi-String Attribute Values of an Object
// This method includes a recursive flag in case you want to recursively dig up properties of properites such as enumerating all the member values of a group and then getting each member group's groups all the way up the tree.
public ArrayList AttributeValuesMultiString(string attributeName,
                         string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                                        en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}

//Enumerate Single String Attribute Values of an Object
public string AttributeValuesSingleString(string attributeName, string objectDn)
{
     string strValue;
     DirectoryEntry ent = new DirectoryEntry(objectDn);
     strValue = ent.Properties[attributeName].Value.ToString();
     ent.Close();
     ent.Dispose();
     return strValue;
}


//Enumerate an Object's Properties (The Ones With Values)
public static ArrayList GetUsedAttributes(string objectDn)
{
    DirectoryEntry objRootDSE = new DirectoryEntry("LDAP://" + objectDn);
    ArrayList props = new ArrayList();
    foreach (string strAttrName in objRootDSE.Properties.PropertyNames)
    {
        props.Add(strAttrName);
    }
    return props;
}



/*
 * Get an Object DistinguishedName (ADO.NET Search) - ADVANCED
 * This method is the glue that ties all the methods together since most all the methods require the consumer to provide a distinguishedName.
 * Where ever you put this code, you must ensure that you also add these enumerations as well. This allows the consumer to specifiy the type of object to search for and whether they want the distinguishedName returned or the objectGUID.
 */
public enum objectClass
{
 user,
 group,
 computer
}
public enum returnType
{
 distinguishedName,
 ObjectGUID
}


/* A call to this class might look like:
 * myObjectReference.GetObjectDistinguishedName(objectClass.user, returnType.ObjectGUID, "john.q.public", "contoso.com")
 * Collapse */
 
public string GetObjectDistinguishedName(objectClass objectCls, 
                                          returnType returnValue,
                                          string objectName,
                                          string LdapDomain)
{
    string distinguishedName = string.Empty;
    string connectionPrefix = "LDAP://" + LdapDomain;
    DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
    DirectorySearcher mySearcher = new DirectorySearcher(entry);

    switch (objectCls)
    {
        case objectClass.user:
            mySearcher.Filter = "(&(objectClass=user)(|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";
            break;
        case objectClass.group:
            mySearcher.Filter = "(&(objectClass=group)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
            break;
        case objectClass.computer:
            mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
            break;
    }
    System.DirectoryServices.SearchResult result = mySearcher.FindOne();

    if (result == null){
        throw new NullReferenceException("unable to locate the distinguishedName for the object " +
                                            objectName + " in the " + LdapDomain + " domain");
    }
    DirectoryEntry directoryObject = result.GetDirectoryEntry();
    if (returnValue.Equals(returnType.distinguishedName)){
        distinguishedName = "LDAP://" + directoryObject.Properties["distinguishedName"].Value;
    }
    if (returnValue.Equals(returnType.ObjectGUID)){
        distinguishedName = directoryObject.Guid.ToString();
    }
    entry.Close();
    entry.Dispose();
    mySearcher.Dispose();
    return distinguishedName;
}


// Convert distinguishedName to ObjectGUID
public string ConvertDNtoGUID(string objectDN)
{
   //Removed logic to check existence first
   DirectoryEntry directoryObject = new DirectoryEntry(objectDN);
   return directoryObject.Guid.ToString();
}

// Convert an ObjectGUID to OctectString (the native ObjectGUID)
public static string ConvertGuidToOctectString(string objectGuid)
{
    System.Guid guid = new Guid(objectGuid);
    byte[] byteGuid = guid.ToByteArray();
    string queryGuid = "";
    foreach (byte b in byteGuid)
    {
        queryGuid += @"\" + b.ToString("x2");
    }
    return queryGuid;
}

//Publish Network Shares in Active Directory
 //Example
 private void init()
        {
            CreateShareEntry("OU=HOME,dc=cathaybk,dc=com", 
                             "Music", 
                             @"\\192.168.2.1\Music", 
                             "mp3 Server Share");
            Console.ReadLine();
        }
        
 //Actual Method       
 public void CreateShareEntry(string ldapPath, 
                                     string shareName,
                                     string shareUncPath,
                                     string shareDescription)
        {
            string oGUID = string.Empty;
            string connectionPrefix = "LDAP://" + ldapPath;
            DirectoryEntry directoryObject = new DirectoryEntry(connectionPrefix);
            DirectoryEntry networkShare = directoryObject.Children.Add("CN=" + shareName, "volume");
            networkShare.Properties["uNCName"].Value = shareUncPath;
            networkShare.Properties["Description"].Value = shareDescription;
            networkShare.CommitChanges();

            directoryObject.Close();
            networkShare.Close();
        }

//Active Directory Users Tasks:
//These methods require these imports
//You must add a references in your project as well


//Add User to Group
 public void AddToGroup(string userDn, string groupDn)
 {
         try
         {
             DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
             dirEntry.Properties["member"].Add(userDn);
             dirEntry.CommitChanges();
             dirEntry.Close();
         }
         catch (System.DirectoryServices.DirectoryServicesCOMException E)
         {
             //doSomething with E.Message.ToString();
             Console.WriteLine(E.Message);
         }
 }


// Remove User From Group
public void RemoveUserFromGroup(string userDn, string groupDn)
{
        try
        {
            DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
            dirEntry.Properties["member"].Remove(userDn);
            dirEntry.CommitChanges();
            dirEntry.Close();
        }
        catch (System.DirectoryServices.DirectoryServicesCOMException E)
        {
            //doSomething with E.Message.ToString();
            Console.WriteLine(E.Message);
        }
}

// Get User Group Memberships of the Logged In User (From ASP.NET)
public ArrayList Groups()
{
     ArrayList groups = new ArrayList();
     foreach (System.Security.Principal.IdentityReference group in
                     System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
     {
         groups.Add(group.Translate(typeof(System.Security.Principal.NTAccount)).ToString());
     }
     return groups;
}

// Get User Group Memberships
// This method requires that you have the AttributeValuesMultiString method earlier in the article included in your class.

public ArrayList Groups(string userDn, bool recursive)
{
    ArrayList groupMemberships = new ArrayList();
    return AttributeValuesMultiString("memberOf", userDn, 
                                         groupMemberships, recursive);
}

//Create User Account
public string CreateUserAccount(string ldapPath, string userName, string userPassword)
{
    string oGUID =string.Empty;
    try
    {
    oGUID = string.Empty;
    string connectionPrefix = "LDAP://" + ldapPath;
    DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
    DirectoryEntry newUser = dirEntry.Children.Add("CN=" + userName, "user");
    newUser.Properties["samAccountName"].Value = userName;
    newUser.CommitChanges();
    oGUID = newUser.Guid.ToString();

    newUser.Invoke("SetPassword", new object[] { userPassword });
    newUser.CommitChanges();
    dirEntry.Close();
    newUser.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException Ex)
    {
        //DoSomethingwith --> E.Message.ToString();
        Console.WriteLine(Ex.Message);
    }
    return oGUID;
}

//Enable a User Account
public void Enable(string userDn)
{
    try
    {
        DirectoryEntry user = new DirectoryEntry(userDn);
        int val = (int)user.Properties["userAccountControl"].Value;
        user.Properties["userAccountControl"].Value = val & ~0x2; //ADS_UF_NORMAL_ACCOUNT;
        user.CommitChanges();
        user.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingWith --> E.Message.ToString();
        Console.WriteLine(E.Message);
    }
}


// Disable a User Account
public void Disable(string userDn)
 {
     try
     {
         DirectoryEntry user = new DirectoryEntry(userDn);
         int val = (int)user.Properties["userAccountControl"].Value;
         user.Properties["userAccountControl"].Value = val | 0x2; //ADS_UF_ACCOUNTDISABLE;
         user.CommitChanges();
         user.Close();
     }
     catch (System.DirectoryServices.DirectoryServicesCOMException E)
     {
         //DoSomethingWith --> E.Message.ToString();
         Console.WriteLine(E.Message);
     }
 }


//Unlock a User Account
public void Unlock(string userDn)
{
    try
    {
        DirectoryEntry uEntry = new DirectoryEntry(userDn);
        uEntry.Properties["LockOutTime"].Value = 0; //unlock account
        uEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingWith --> E.Message.ToString();
        Console.WriteLine(E.Message);
    }
}

//Reset a User password
public void ResetPassword(string userDn, string password)
{
    DirectoryEntry uEntry = new DirectoryEntry(userDn);
    uEntry.Invoke("SetPassword", new object[] { password });
    uEntry.Properties["LockOutTime"].Value = 0; //unlock account
    uEntry.Close();
}


}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us