This class represent a domain
        /// < Admin Update>
        /// Update a existing admin.
        /// </summary>
        /// <param name="user">Set Values in a Admin Class Property and Pass the Object of Admin Class.</param>
        public static void Update(Domain.Myfashion.Domain.Admin user)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction. 
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        // Proceed Sction to update Data.
                        // And Set the reuired paremeters to find the specific values. 
                        int i = session.CreateQuery("Update Admin set Image =:profileurl, UserName =: username , TimeZone=:timezone,FirstName =:first,LastName =:last  where Id = :twtuserid")
                                  .SetParameter("twtuserid", user.Id)
                                  .SetParameter("profileurl", user.Image)
                                  .SetParameter("username", user.UserName)
                                  .SetParameter("timezone", user.TimeZone)
                                  .SetParameter("first",user.FirstName)
                                  .SetParameter("last",user.LastName)
                                  .ExecuteUpdate();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);

                    }
                }//End Using trasaction
            }//End Using session
        }
Esempio n. 2
0
        public async Task<IHttpActionResult> PostRestaurant(Domain.Entities.Restaurant restaurant)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Restaurants.Add(restaurant);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (RestaurantExists(restaurant.ID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = restaurant.ID }, restaurant);
        }
        public bool IsFbPagePostCommentLikerExist(Domain.Myfashion.Domain.FbPagePostCommentLiker _FbPagePostCommentLiker)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    //Proceed action, to save data.
                    try
                    {
                        //Proceed action to, get all wall post of Facebook User.
                        List<Domain.Myfashion.Domain.FbPagePostCommentLiker> alst = session.CreateQuery("from FbPagePostCommentLiker where UserId = :userid and FromId = :fromid and CommentId = :commentid")
                         .SetParameter("userid", _FbPagePostCommentLiker.UserId)
                         .SetParameter("fromid", _FbPagePostCommentLiker.FromId)
                         .SetParameter("commentid", _FbPagePostCommentLiker.CommentId)
                         .List<Domain.Myfashion.Domain.FbPagePostCommentLiker>()
                         .ToList<Domain.Myfashion.Domain.FbPagePostCommentLiker>();
                        if (alst.Count > 0)
                            return true;
                        else
                            return false;

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return true;
                    }
                }//End Transaction
            }//End session
        }
Esempio n. 4
0
        public void CreateNewTask(string description, string userid, Domain.Socioboard.Domain.Tasks task, string assigntoId, string comment)
        {
            string descritption = description;
            Guid idtoassign = Guid.Empty;
            idtoassign = Guid.Parse(assigntoId);

            Domain.Socioboard.Domain.Tasks objTask = task;
            TaskRepository objTaskRepo = new TaskRepository();
            objTask.AssignDate = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss").ToString();
            objTask.AssignTaskTo = idtoassign;
            objTask.TaskStatus = false;
            objTask.TaskMessage = descritption;
            objTask.UserId = Guid.Parse(userid);
            Guid taskid = Guid.NewGuid();
            objTask.Id = taskid;
            objTaskRepo.addTask(objTask);

            /////////////////       
            string Comment = comment;
            if (!string.IsNullOrEmpty(comment))
            {
                string curdate = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss").ToString();
                Domain.Socioboard.Domain.TaskComment objcmt = new Domain.Socioboard.Domain.TaskComment();
                TaskCommentRepository objcmtRepo = new TaskCommentRepository();
                objcmt.Comment = comment;
                objcmt.CommentDate = DateTime.Now;
                objcmt.EntryDate = DateTime.Now;
                objcmt.Id = Guid.NewGuid();
                objcmt.TaskId = objTask.Id;
                objcmt.UserId = Guid.Parse(userid);
                objcmtRepo.addTaskComment(objcmt);
            }
        }
Esempio n. 5
0
        public async Task<IHttpActionResult> PutRestaurant(Guid id, Domain.Entities.Restaurant restaurant)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != restaurant.ID)
            {
                return BadRequest();
            }

            db.Entry(restaurant).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RestaurantExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
        /// <updateInstagramUser>
        /// update InstagramUser account.
        /// </summary>
        /// <param name="insaccount">Set Values in a InstagramAccount Class Property and Pass the same Object of InstagramAccount Class.(Domain.InstagramAccount)</param>
        public void updateInstagramUser(Domain.Socioboard.Domain.InstagramAccount insaccount)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {

                    //Proceed action to Update InstagrameAccount
                    // And Set the reuired paremeters to find the specific values.
                    try
                    {
                        session.CreateQuery("Update InstagramAccount set InsUserName =:InsUserName,ProfileUrl=:ProfileUrl,AccessToken =:AccessToken,Followers =:Followers,FollowedBy=:FollowedBy,TotalImages=:TotalImages where InstagramId = :InstagramId and UserId = :userid")
                            .SetParameter("InsUserName", insaccount.InsUserName)
                            .SetParameter("ProfileUrl", insaccount.ProfileUrl)
                            .SetParameter("AccessToken", insaccount.AccessToken)
                            .SetParameter("Followers", insaccount.Followers)
                            .SetParameter("FollowedBy", insaccount.FollowedBy)
                            .SetParameter("TotalImages", insaccount.TotalImages)
                            .SetParameter("InstagramId", insaccount.InstagramId)
                            .SetParameter("userid", insaccount.UserId)
                            .ExecuteUpdate();
                        transaction.Commit();


                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        // return 0;
                    }
                }//End Transaction
            }//End session
        }
Esempio n. 7
0
        public void Composites()
        {
            var metaPopulation = new MetaPopulation();
            var domain = new Domain(metaPopulation, Guid.NewGuid());
            var superdomain = new Domain(metaPopulation, Guid.NewGuid());
            domain.AddDirectSuperdomain(superdomain);

            Assert.AreEqual(0, metaPopulation.Composites.Count());

            var @class = new ClassBuilder(domain, Guid.NewGuid()).WithSingularName("Class").WithPluralName("Classes").Build();

            Assert.AreEqual(1, metaPopulation.Composites.Count());

            var superclass = new ClassBuilder(superdomain, Guid.NewGuid()).WithSingularName("Superclass").WithPluralName("Superclasses").Build();

            Assert.AreEqual(2, metaPopulation.Composites.Count());

            var @interface = new InterfaceBuilder(domain, Guid.NewGuid()).WithSingularName("i1").WithPluralName("i1s").Build();

            Assert.AreEqual(3, metaPopulation.Composites.Count());

            var superinterface = new InterfaceBuilder(superdomain, Guid.NewGuid()).WithSingularName("i2").WithPluralName("i2s").Build();

            Assert.AreEqual(4, metaPopulation.Composites.Count());

            var unit = new UnitBuilder(domain, UnitIds.StringId).WithSingularName("AllorsString").WithPluralName("AllorsStrings").WithUnitTag(UnitTags.AllorsString).Build();

            Assert.AreEqual(4, metaPopulation.Composites.Count());

            var superunit = new UnitBuilder(domain, UnitIds.IntegerId).WithSingularName("AllorsInteger").WithPluralName("AllorsIntegers").WithUnitTag(UnitTags.AllorsString).Build();

            Assert.AreEqual(4, metaPopulation.Composites.Count());
        }
Esempio n. 8
0
        public static Key CreateKey(string id, Domain domain, string name, Type type, object defaultVal)
        {
            Key key = null;

              if (type == typeof(bool))
              {
              key = new BooleanKey(id, domain, name, (bool)defaultVal);
              }
              else if (type == typeof(int))
              {
              key = new IntegerKey(id, domain, name, (int)defaultVal);
              }
              else if (type == typeof(long))
              {
              key = new LongKey(id, domain, name, (long)defaultVal);
              }
              else if (type == typeof(float))
              {
              key = new FloatKey(id, domain, name, (float)defaultVal);
              }
              else if (type == typeof(double))
              {
              key = new DoubleKey(id, domain, name, (double)defaultVal);
              }
              else if (type == typeof(string))
              {
              key = new StringKey(id, domain, name, (string)defaultVal);
              }

              return key;
        }
        public bool checkTubmlrUserExists(Domain.Socioboard.Domain.TumblrAccount objTumblrAccount)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        //Proceed action, to Check if FacebookUser is Exist in database or not by UserId and FbuserId.
                        // And Set the reuired paremeters to find the specific values.
                        NHibernate.IQuery query = session.CreateQuery("from TumblrAccount where UserId = :uidd and tblrUserName = :tbuname");
                        query.SetParameter("uidd",objTumblrAccount.UserId);
                        query.SetParameter("tbuname", objTumblrAccount.tblrUserName);
                        var result = query.UniqueResult();

                        if (result == null)
                            return false;
                        else
                            return true;

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return true;
                    }

                }//End Transaction
            }//End session
        }
 /// <DeleteGroup>
 /// Delete a group of user by profile id , group id and profile id.
 /// </summary>
 /// <param name="group">Set the group name and user id in a Groups Class Property and Pass the same Object of Groups Class.(Domain.Groups)</param>
 /// <returns>Return 1 when Data  is deleted Otherwise retun 0. (int)</returns>
 public int DeleteGroup(Domain.Myfashion.Domain.Groups group)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to delete the group data.
                 NHibernate.IQuery query = session.CreateQuery("delete from Groups where UserId = :userid and GroupName = :name")
                                 .SetParameter("name", group.GroupName)
                                 .SetParameter("userid", group.UserId);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return isUpdated;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return 0;
             }
         }//End Transaction
     }//End Session
 }
Esempio n. 11
0
        public static Key CreateKey(string id, Domain domain, string name, string attibType, object defaultVal)
        {
            Key key = null;

             if (attibType.ToLower() == XMLConstants._Bool)
             {
            key = new BooleanKey(id, domain, name, (bool)defaultVal);
             }
             else if (attibType.ToLower() == XMLConstants._Int)
             {
             key = new IntegerKey(id, domain, name, (int)defaultVal);
             }
             else if (attibType.ToLower() == XMLConstants._Long)
             {
             key = new LongKey(id, domain, name, (long)defaultVal);
             }
             else if (attibType.ToLower() == XMLConstants._Float)
             {
             key = new FloatKey(id, domain, name, (float)defaultVal);
             }
             else if (attibType.ToLower() == XMLConstants._Double)
             {
             key = new DoubleKey(id, domain, name, (double)defaultVal);
             }
             else if (attibType.ToLower() == XMLConstants._String)
             {
             key = new StringKey(id, domain, name, (string)defaultVal);
             }

             return key;
        }
Esempio n. 12
0
 protected BaseEmailEngager(Context context, IWebElement listItem) : base(context)
 {
     ListItem = listItem;
     DomainName = GetDomainName(listItem);
     CurrentDomain = context.GetDomain(DomainName);
     context.CurrentDomain = CurrentDomain;
 }
 public static void SaveSensorData(Domain.SensorData sd) {
      SqlConnection connection = new SqlConnection(CN);
      SqlCommand insert = new SqlCommand();
      SqlParameter nodeId, timeStamp, powerLevel, motionDetected;
      insert.CommandText = "INSERT INTO [SensorFeed] (NodeID, TimeStamp, PowerLevel, MotionDetected) VALUES (@NodeID, @TimeStamp, @PowerLevel, @MotionDetected)";
      nodeId = new SqlParameter("@NodeID", System.Data.SqlDbType.Int);
      nodeId.Value = sd.NodeId;
      timeStamp = new SqlParameter("@TimeStamp", System.Data.SqlDbType.DateTime);
      timeStamp.Value = sd.TimeStamp;
      powerLevel = new SqlParameter("@PowerLevel", System.Data.SqlDbType.Float);
      powerLevel.Value = sd.PowerLevel;
      motionDetected = new SqlParameter("@MotionDetected", System.Data.SqlDbType.Bit);
      motionDetected.Value = 0;
      insert.Parameters.Add(nodeId);
      insert.Parameters.Add(timeStamp);
      insert.Parameters.Add(powerLevel);
      insert.Parameters.Add(motionDetected);
      insert.Connection = connection;
      try {
           connection.Open();
           insert.ExecuteNonQuery();
      } catch (Exception ex) {
           System.Diagnostics.Debug.WriteLine(ex.Message);
      } finally {
           connection.Close();
           insert.Dispose();
           connection.Dispose();
      }
 }
Esempio n. 14
0
 public MvcRolePermissionService(Domain.Repository.IMvcControllerRolePermissionRepository permission,
     Domain.Repository.IMvcControllerActionRepository action,
     Domain.Repository.IMvcControllerClassRepository controllerClass,
     Domain.Repository.IMvcControllerRepository controller,
     Domain.Repository.IRolesRepository role)
 {
     if (permission == null)
     {
         throw new ArgumentNullException("permissionService is null");
     }
     if (action == null)
     {
         throw new ArgumentNullException("actionRepository is null");
     }
     if (controllerClass == null)
     {
         throw new ArgumentNullException("controllerClassRepository is null");
     }
     if (controller == null)
     {
         throw new ArgumentNullException("controllerRepository is null");
     }
     if (role == null)
     {
         throw new ArgumentNullException("roleRepository is null");
     }
     permissionRepository = permission;
     actionRepository = action;
     controllerClassRepository = controllerClass;
     controllerRepository = controller;
     roleRepository = role;
 }
Esempio n. 15
0
    } // End of the GetConnectionString method

    /// <summary>
    /// Get the current domain
    /// </summary>
    /// <returns>The current domain, a empty domain if it is null</returns>
    public static Domain GetCurrentDomain()
    {
        // Get the domain name
        string domainName = HttpContext.Current.Request.Url.Host;

        // Replace www.
        domainName = domainName.Replace("www.", "");

        // Get the domain post
        Domain domain = Domain.GetOneByDomainName(domainName);

        // Make sure that the domain not is null
        if(domain == null)
        {
            domain = new Domain();
            domain.id = 0;
            domain.domain_name = "localhost";
            domain.web_address = "https://localhost:80";
            domain.front_end_language = 2;
            domain.back_end_language = 2;
            domain.custom_theme_id = 0;
            domain.analytics_tracking_id = "";
            domain.facebook_app_id = "";
            domain.facebook_app_secret = "";
            domain.google_app_id = "";
            domain.google_app_secret = "";
            domain.noindex = true;
        }

        // Return the current front end language id
        return domain;

    } // End of the GetCurrentDomain method
 /// <summary>
 /// Stores the location object in the db of known locations
 /// </summary>
 /// <param name="location">location object to store, required fields should be populated</param>
 public void StoreAsKnownLocation(Domain.Location.Location location)
 {
     //Forces proxy loading
     location.GetType();
     location.LocationSensorDatas = CurrentLocation.LocationSensorDatas;
     _locations.Add(location);
 }
        /// <summary>
        /// This method return the default domain for single domain scenarios (this is necessary because the ratings for each user is added to a domain)
        /// (should be tested)
        /// </summary>
        /// <returns></returns>
        public static Domain GetDefualtDomain()
        {
            if (_defaultDomain == null)
                _defaultDomain = new Domain("default");

            return _defaultDomain;
        }
Esempio n. 18
0
        protected override void PerformAdmin(Domain.IncomingSmsMessage message)
        {
            string newIdea;
            if (TryCrackMessage(message.Message, out newIdea))
            {
                IDataStore store = DataStore.GetInstance();
                DailyIdea idea = store.DailyIdeas.Where(i => i.Idea == newIdea).FirstOrDefault();

                if (idea == null)
                {
                    idea = new DailyIdea
                    {
                        Idea = newIdea,
                    };
                    store.Save(idea);

                    Say(message.From, SmsResponseStrings.Add_Success_AddedNewIdea(idea.Id));
                }
                else
                {
                    Say(message.From, SmsResponseStrings.Add_Failed_ExistingIdea(idea.Id));
                }
            }
            else
            {
                Say(message.From, SmsResponseStrings.Add_Help());
            }
        }
        public bool AddDemoRequest(Domain.Socioboard.Domain.Demorequest demoReq)
        {
            bool IsSuccess = false;
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    //Proceed action, to Save data.
                    try
                    {
                        session.Save(demoReq);
                        transaction.Commit();
                        IsSuccess = true;
                        return IsSuccess;
                    }
                    catch (Exception ex)
                    {

                        Console.WriteLine(ex.StackTrace);
                        return IsSuccess;
                    }

                }//End Transaction
            }//End Session
        }
Esempio n. 20
0
 /// <DeleteDrafts>
 /// Delete Draft
 /// </summary>
 /// <param name="d">Set Values in a Draft Class Property and Pass the Object of Draft Class (SocioBoard.Domain.Draft).</param>
 /// <returns>Return 1 for successfully deleted or 0 for failed.</returns>
 public int DeleteDrafts(Domain.Socioboard.Domain.Drafts d)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //Begin session trasaction and opens up.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action , 
                 //To delete draft, by user id and message.
                 NHibernate.IQuery query = session.CreateQuery("delete from Drafts where UserId = :userid and Message =:mess")
                                 .SetParameter("userid", d.UserId)
                                 .SetParameter("mess", d.Message);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return isUpdated;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return 0;
             }
         }//End transaction
     }//End session
 }
Esempio n. 21
0
        private void SayLastError(Domain.IncomingSmsMessage message)
        {
            IDataStore store = DataStore.GetInstance();

            LogItem lastError = store.LogItems.Where(l => l.Exception != null).OrderByDescending(l => l.Date).FirstOrDefault();
            if (lastError != null)
            {
                Say(message.From, "Error entry {0} at occurred at {1} (UTC)",
                    lastError.ID,
                    lastError.Date);

                if(!string.IsNullOrEmpty(lastError.Message))
                {
                    Say(message.From, SubOrNull(lastError.Message, 0, 140));
                }

                // send at most 3 messages
                List<string> parts = new List<string>();
                parts.Add(SubOrNull(lastError.Exception, 0, 140));
                parts.Add(SubOrNull(lastError.Exception, 140, 140));
                parts.Add(SubOrNull(lastError.Exception, 280, 140));

                foreach (string part in parts)
                {
                    if (part != null)
                    {
                        Say(message.From, part);
                    }
                }
            }
            else
            {
                Say(message.From, "No errors in the log.  Hurray?");
            }
        }
        public Domain.ErrorCode Execute(Domain.Values.Configuration configuration, Domain.Values.ExecutionPlan executionPlan)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (executionPlan == null)
            {
                throw new ArgumentNullException("executionPlan");
            }

            try
            {
                var scripts = Domain.Factories.ScriptFactory.Create(configuration, executionPlan, configInjector);
                executionPlan.DatabaseAdapter.Initialize();
                foreach(var script in scripts)
                {
                    var errorCode = script.Run(executionPlan.DatabaseAdapter);
                    if (Domain.ErrorCode.Ok != errorCode)
                    {
                        log.ErrorFormat(CultureInfo.InvariantCulture, "Script \"{0}\" failed; subsequent scripts will not run.", script.Name);
                        return errorCode;
                    }
                }

                return Domain.ErrorCode.Ok;
            }
            catch (Domain.DatabaseScripterException ex)
            {
                log.Error("An error occurred. Check the debug information that follows.", ex);
                return ex.ErrorCode;
            }
        }
Esempio n. 23
0
        public void ReadKey(string keyId, Domain domain, string keyName, Type dataType, object defaultVal, string inputStr)
        {
            //<key id="nd0" for="node" attr.name="X1" attr.type="string" />

            var keyReader = new KeyReader();
            var reader = new XmlTextReader(new StringReader(inputStr));
            reader.Read();
            Assert.True(reader.IsStartElement());
            Assert.True(string.Compare("key", reader.Name, true) == 0, string.Format("Reader.Name should match expected, not: \"{0}\"", reader.Name));

            string retrievedKeyId;
            Domain retrievedDomain;
            string retrievedAttribName;
            Type retrievedType;
            object retrievedDefault;
            keyReader.Read(out retrievedKeyId, out retrievedDomain, out retrievedAttribName, out retrievedType, out retrievedDefault, reader);

            Assert.Equal(keyId, retrievedKeyId);
            Assert.Equal(domain, retrievedDomain);
            Assert.Equal(keyName, retrievedAttribName);
            Assert.Equal(dataType, retrievedType);
            Assert.Equal(defaultVal, retrievedDefault);

            if (!reader.IsEmptyElement)
                Assert.True(string.Compare("key", reader.Name, true) == 0, string.Format("End Reader.Name should match expected, not: \"{0}\"", reader.Name));
        }
Esempio n. 24
0
        protected override void PerformAdmin(Domain.IncomingSmsMessage message)
        {
            int id;
            if (TryCrackId(message.Message, out id))
            {
                IDataStore store = DataStore.GetInstance();
                Subscription sub = store.Subscriptions.Where(s => s.Id == id).FirstOrDefault();

                if (sub != null)
                {
                    Say(message.From, "Subscription {0} has phone {1} and is due on {2}",
                        sub.Id,
                        sub.Phone,
                        sub.Next);
                }
                else
                {
                    Say(message.From, "Subscription Not Found: {0}", id);
                }
            }
            else
            {
                Say(message.From, "Unable to parse input.  Usage: SUB <id>   Example:  SUB 10");
            }
        }
 /// <deleteTwitterMessage>
 /// Delete Twitter Message
 /// </summary>
 /// <param name="twtmsg">Set Values of profile id and user id in a TwitterMessage Class Property and Pass the Object of Class.(Domein.TwitterMessage)</param>
 /// <returns>Return 1 for success and 0 for failure.(int) </returns>
 public int deleteTwitterMessage(Domain.Myfashion.Domain.TwitterMessage twtmsg)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, open up a Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to delete twitter message by twitter user id and user id 
                 NHibernate.IQuery query = session.CreateQuery("delete from TwitterMessage where ProfileId = :twtuserid and UserId = :userid")
                                 .SetParameter("twtuserid", twtmsg.ProfileId)
                                 .SetParameter("userid", twtmsg.UserId);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return isUpdated;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return 0;
             }
         }//End Transaction
     }//End Session
 }
 /// <DeleteArchiveMessage>
 /// Delete a ArchieveMessage From Database by UserId and Message.
 /// </summary>
 /// <param name="archive">the object of the ArchieveMessage class(Domain.ArchieveMEssage)</param>
 /// <returns>Return 1 for True and 0 for False</returns>
 public int DeleteArchiveMessage(Domain.Socioboard.Domain.ArchiveMessage archive)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction. 
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 // Proceed action to Detele specific data.
                 // return the integer value when it is success or not (0 or 1).
                 NHibernate.IQuery query = session.CreateQuery("delete from ArchiveMessage where UserId = :userid and Message = :message")
                                 .SetParameter("message", archive.Message)
                                 .SetParameter("userid", archive.UserId);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return isUpdated;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return 0;
             }
         }// End using trasaction
     }// End using session
 }
 public AccessionOrderDataSheetDataCommentLog(Domain.OrderCommentLog orderCommentLog)
 {
     this.m_LoggedBy = string.IsNullOrEmpty(orderCommentLog.LoggedBy) ? orderCommentLog.LoggedBy : string.Empty;
     this.m_Description = string.IsNullOrEmpty(orderCommentLog.Description) ? orderCommentLog.Description : string.Empty;
     this.m_Comment = string.IsNullOrEmpty(orderCommentLog.Comment) ? orderCommentLog.Comment : string.Empty;
     this.m_LogDate = orderCommentLog.LogDate.ToShortDateString() + " " + orderCommentLog.LogDate.ToShortTimeString();
 }
Esempio n. 28
0
 public static BasketResource FromBasket(Domain.Basket basket)
 {
     return new BasketResource
                {
                    Id = basket.Id
                };
 }
 /// <updateGooglePlusUser>
 /// Update google pluse user account details.
 /// </summary>
 /// <param name="gpaccount">Set Values in a GooglePlusAccount Class Property and Pass the same Object of GooglePlusAccount Class.(Domain.GooglePlusAccount)</param>
 public void updateGooglePlusUser(Domain.Socioboard.Domain.GooglePlusAccount gpaccount)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to update google pluse account details
                 session.CreateQuery("Update GooglePlusAccount set GpUserName =:gpusername,AccessToken =:access,RefreshToken=:refreshtoken,GpProfileImage =:gpprofileimage,RefreshToken=:refreshtoken,EmailId=:emailid where GpUserId = :gpuserid and UserId = :userid")
                     .SetParameter("gpusername", gpaccount.GpUserName)
                     .SetParameter("access", gpaccount.AccessToken)
                     .SetParameter("refreshtoken",gpaccount.RefreshToken)
                     .SetParameter("gpprofileimage", gpaccount.GpProfileImage)
                     .SetParameter("emailid", gpaccount.EmailId)
                     .SetParameter("fbuserid", gpaccount.GpUserId)
                     .SetParameter("userid", gpaccount.UserId)
                     .ExecuteUpdate();
                 transaction.Commit();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 // return 0;
             }
         }//End Transaction 
     }//End Session
 }
 /// <deleteTeamMember>
 /// Delete profile of TeamMember
 /// </summary>
 /// <param name="team">Set the team id and prfile id of team in a TeamMemberProfile Class Property and Pass the Object of TeamMemberProfile Class.(Domein.TeamMemberProfile)</param>
 /// <returns>Return 1 for successfully delete and 0 for failed.(int)</returns>
 public int deleteTeamMember(Domain.Socioboard.Domain.TeamMemberProfile team)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to deleting team profile by id and team id.
                 NHibernate.IQuery query = session.CreateQuery("delete from TeamMemberProfile where TeamId = :teamid and ProfileId = :profileid")
                                 .SetParameter("teamin", team.TeamId)
                                 .SetParameter("profileid", team.ProfileId);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return isUpdated;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return 0;
             }
         }//End Transaction
     }//End Session
 }
Esempio n. 31
0
        //Change ParentID to the actual Parent Object
        static async Task <Domain> RecusiveDomainsAdd(DomainDTO domain, DataContext db, IEnumerable <Domain> originalDomains)
        {
            var domainCheck = originalDomains.Where(x => x.ID == domain.ID).FirstOrDefault();

            if (domainCheck == null)
            {
                domainCheck = new Domain()
                {
                    ID           = Lpp.Utilities.DatabaseEx.NewGuid(),
                    DataType     = domain.DataType,
                    EnumValue    = domain.EnumValue,
                    IsMultiValue = domain.IsMultiValue,
                    Title        = domain.Title,
                };
                db.Domains.Add(domainCheck);
            }
            else
            {
                domainCheck.DataType       = domain.DataType;
                domainCheck.EnumValue      = domain.EnumValue;
                domainCheck.IsMultiValue   = domain.IsMultiValue;
                domainCheck.ParentDomainID = domain.ParentDomainID;
                domainCheck.Title          = domain.Title;
            }

            if (domain.References != null && domain.References.Count() > 0)
            {
                foreach (var reff in domain.References)
                {
                    var refCheck = domainCheck.DomainReferences.Where(x => x.ID == reff.ID).FirstOrDefault();
                    if (refCheck == null)
                    {
                        refCheck = new DomainReference()
                        {
                            ID                      = Lpp.Utilities.DatabaseEx.NewGuid(),
                            Title                   = reff.Title,
                            Description             = reff.Description,
                            DomainID                = domainCheck.ID,
                            ParentDomainReferenceID = reff.ParentDomainReferenceID
                        };
                        domainCheck.DomainReferences.Add(refCheck);
                    }
                    else
                    {
                        refCheck.Title                   = reff.Title;
                        refCheck.Description             = reff.Description;
                        refCheck.DomainID                = domainCheck.ID;
                        refCheck.ParentDomainReferenceID = reff.ParentDomainReferenceID;
                    }
                }
            }

            if (domain.ChildMetadata != null && domain.ChildMetadata.Count() > 0)
            {
                foreach (var child in domain.ChildMetadata)
                {
                    var cc = await RecusiveDomainsAdd(child, db, originalDomains);

                    cc.ParentDomainID = domainCheck.ID;
                    domainCheck.ChildrenDomains.Add(cc);
                }
            }

            //await db.SaveChangesAsync();
            return(domainCheck);
        }
Esempio n. 32
0
        // If originalConnector != null, use that connector for AddConnection routine, instead of connector.
        private static void ProcessConnections(ExporterIFC exporterIFC, Connector connector, Connector originalConnector)
        {
            // Port connection is not allowed for IFC4RV MVD
            bool isIFC4AndAbove = !ExporterCacheManager.ExportOptionsCache.ExportAsOlderThanIFC4;

            Domain domain             = connector.Domain;
            bool   isElectricalDomain = (domain == Domain.DomainElectrical);
            bool   supportsDirection  = (domain == Domain.DomainHvac || domain == Domain.DomainPiping);

            ConnectorType connectorType = connector.ConnectorType;

            if (connectorType == ConnectorType.End ||
                connectorType == ConnectorType.Curve ||
                connectorType == ConnectorType.Physical)
            {
                Connector         originalConnectorToUse = originalConnector ?? connector;
                FlowDirectionType flowDirection          = supportsDirection ? connector.Direction : FlowDirectionType.Bidirectional;
                bool isBiDirectional = (flowDirection == FlowDirectionType.Bidirectional);
                if (connector.IsConnected)
                {
                    ConnectorSet         connectorSet = connector.AllRefs;
                    ConnectorSetIterator csi          = connectorSet.ForwardIterator();

                    while (csi.MoveNext())
                    {
                        Connector connected = csi.Current as Connector;
                        if (connected != null && connected.Owner != null && connector.Owner != null)
                        {
                            if (connected.Owner.Id != connector.Owner.Id)
                            {
                                // look for physical connections
                                ConnectorType connectedType = connected.ConnectorType;
                                if (connectedType == ConnectorType.End ||
                                    connectedType == ConnectorType.Curve ||
                                    connectedType == ConnectorType.Physical)
                                {
                                    if (flowDirection == FlowDirectionType.Out)
                                    {
                                        AddConnection(exporterIFC, connected, originalConnectorToUse, false, isElectricalDomain);
                                    }
                                    else
                                    {
                                        AddConnection(exporterIFC, originalConnectorToUse, connected, isBiDirectional, isElectricalDomain);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    Element hostElement = connector.Owner;

                    IFCFlowDirection flowDir = (isBiDirectional) ? IFCFlowDirection.SourceAndSink : (flowDirection == FlowDirectionType.Out ? IFCFlowDirection.Source : IFCFlowDirection.Sink);
                    IFCAnyHandle     hostElementIFCHandle = ExporterCacheManager.MEPCache.Find(hostElement.Id);
                    string           guid = GUIDUtil.GenerateIFCGuidFrom(IFCEntityType.IfcDistributionPort,
                                                                         connector.Id.ToString(), hostElementIFCHandle);

                    IFCAnyHandle localPlacement = CreateLocalPlacementForConnector(exporterIFC, connector, hostElementIFCHandle, flowDir);
                    IFCFile      ifcFile        = exporterIFC.GetFile();
                    IFCAnyHandle ownerHistory   = ExporterCacheManager.OwnerHistoryHandle;
                    IFCAnyHandle port           = IFCInstanceExporter.CreateDistributionPort(exporterIFC, null, guid,
                                                                                             ownerHistory, localPlacement, null, flowDir);
                    string portType = "Flow"; // Assigned as Port.Description
                    ExporterCacheManager.MEPCache.CacheConnectorHandle(connector, port);
                    SetDistributionPortAttributes(port, connector, portType, hostElement.Id, ref flowDir);

                    // Port connection is changed in IFC4 to use IfcRelNests for static connection. IfcRelConnectsPortToElement is used for a dynamic connection and it is restricted to IfcDistributionElement
                    // The following code collects the ports that are nested to the object to be assigned later
                    if (isIFC4AndAbove)
                    {
                        AddNestedMembership(hostElementIFCHandle, port);
                    }
                    else
                    {
                        // Attach the port to the element
                        string relGuid        = GUIDUtil.GenerateIFCGuidFrom(IFCEntityType.IfcRelConnectsPortToElement, connector.Id.ToString(), port);
                        string connectionName = hostElement.Id + "|" + guid;
                        IFCInstanceExporter.CreateRelConnectsPortToElement(ifcFile, relGuid, ownerHistory, connectionName, portType, port, hostElementIFCHandle);
                    }

                    HashSet <MEPSystem> systemList = new HashSet <MEPSystem>();
                    try
                    {
                        MEPSystem system = connector.MEPSystem;
                        if (system != null)
                        {
                            systemList.Add(system);
                        }
                    }
                    catch
                    {
                    }

                    if (isElectricalDomain)
                    {
                        foreach (MEPSystem system in systemList)
                        {
                            ExporterCacheManager.SystemsCache.AddElectricalSystem(system.Id);
                            ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, hostElementIFCHandle);
                            ExporterCacheManager.SystemsCache.AddHandleToElectricalSystem(system.Id, port);
                        }
                    }
                    else
                    {
                        foreach (MEPSystem system in systemList)
                        {
                            ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, hostElementIFCHandle);
                            ExporterCacheManager.SystemsCache.AddHandleToBuiltInSystem(system, port);
                        }
                    }
                }
            }
        }
Esempio n. 33
0
 public void NestedSessionReuse()
 {
     Domain.Execute(session1 => Domain.Execute(session2 => Assert.That(session1, Is.SameAs(session2))));
 }
        public void Test01()
        {
            var expectedAuthorsCount = 5;
            var booksPerAuthor       = 2;
            var commentsPerBook      = 1;
            var expectedStoresCount  = 1;

            using (var session = Domain.OpenSession()) {
                using (var transaction = session.OpenTransaction()) {
                    var authors = new List <Author>();
                    var stores  = new List <Store>();
                    var store   = new Store();
                    for (var i = 0; i < expectedAuthorsCount; i++)
                    {
                        var author = new Author {
                            Name = string.Format("Author {0}", i)
                        };
                        for (var j = 0; j < booksPerAuthor; j++)
                        {
                            author.Books.Add(new Book {
                                Title = string.Format("Book {0} of Author {1}", j, i)
                            });
                        }

                        foreach (var book in author.Books)
                        {
                            new Comment {
                                Book = book
                            };
                            store.Books.Add(book);
                        }
                        authors.Add(author);
                    }
                    var states = session.EntityChangeRegistry.GetItems(PersistenceState.New).ToList();

                    foreach (var state in states.Where(state => !state.Type.IsAuxiliary))
                    {
                        Assert.IsTrue(state.Key.IsTemporary(Domain));
                    }

                    session.SaveChanges();

                    Assert.AreEqual(store.Books.Count, expectedAuthorsCount * booksPerAuthor);

                    foreach (var author in authors)
                    {
                        Assert.IsFalse(author.Key.IsTemporary(Domain));
                        Assert.Greater(author.Id, 0);
                        foreach (var book in author.Books)
                        {
                            Assert.IsFalse(book.Key.IsTemporary(Domain));
                            Assert.Greater(book.Id, 0);
                            Assert.AreEqual(book.Stores.Count, 0);
                            foreach (var comment in book.Comments)
                            {
                                Assert.IsFalse(comment.Key.IsTemporary(Domain));
                                Assert.Greater(comment.Id, 0);
                            }
                        }
                    }
                    transaction.Complete();
                }
            }
        }
 public override Role GetEveryoneRole(Domain domain)
 {
     return(this.IsLocalProviderSet() ? this.LocalProvider.Value.GetEveryoneRole(domain) : base.GetEveryoneRole(domain));
 }
 public override bool IsEveryoneRole(string accountName, Domain domain)
 {
     return(this.IsLocalProviderSet() ? this.LocalProvider.Value.IsEveryoneRole(accountName, domain) : base.IsEveryoneRole(accountName, domain));
 }
Esempio n. 37
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            bool authentic = false;

            try
            {
                DirectoryEntry entry        = new DirectoryEntry("LDAP://" + Convert.ToString(Domain.GetComputerDomain()), tbUsername.Text, tbPassword.Text);
                object         nativeObject = entry.NativeObject;
                authentic        = true;
                Session["entry"] = entry;
                DirectorySearcher ds = new DirectorySearcher(entry);
                ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + tbUsername.Text + "))";

                ds.SearchScope     = SearchScope.Subtree;
                ds.ServerTimeLimit = TimeSpan.FromSeconds(90);

                SearchResult userObject = ds.FindOne();
                if (authentic == true && userObject != null)
                {
                    Session["username"]     = tbUsername.Text;
                    Session["directsearch"] = userObject;
                    int pagina = ddlApplicatie.SelectedIndex;
                    switch (pagina)
                    {
                    case 0: Response.Redirect("Systeembeheer.aspx");
                        break;

                    case 1: Response.Redirect("Verhuur.aspx");
                        break;

                    case 2: Response.Redirect("Reservatie.aspx");
                        break;

                    case 3: Response.Redirect("SMS.aspx");
                        break;

                    case 4: Response.Redirect("Toegangscontrole.aspx");
                        break;

                    default: Response.Redirect("Home.aspx");
                        break;
                    }
                }
            }
            catch (DirectoryServicesCOMException)
            {
            }
        }
Esempio n. 38
0
 protected DomainBasedRow(Domain domain, DataTable table, string parentID)
     : this(domain, table)
 {
     if (parentID != null)
         this.fields[CremaSchema.__ParentID__] = parentID;
 }
Esempio n. 39
0
 protected DomainBasedRow(Domain domain, DataRow row)
 {
     this.domain = domain ?? throw new ArgumentNullException(nameof(domain));
     this.row = row;
     this.table = row.Table;
 }
Esempio n. 40
0
 public void NewTenant(string name, string domain)
 {
     _db.Database.ExecuteSqlRaw("PNewTenant @p0, @p1, @p2", parameters: new[] { name, Domain.GetDomainHash(domain), domain });
 }
Esempio n. 41
0
        internal static void GetProps(SearchResultEntry entry, ResolvedEntry resolved, ref Domain obj)
        {
            if (!Utils.IsMethodSet(ResolvedCollectionMethod.ObjectProps))
            {
                return;
            }

            obj.Properties.Add("description", entry.GetProp("description"));
            if (!int.TryParse(entry.GetProp("msds-behavior-version"), out var level))
            {
                level = -1;
            }
            string func;

            switch (level)
            {
            case 0:
                func = "2000 Mixed/Native";
                break;

            case 1:
                func = "2003 Interim";
                break;

            case 2:
                func = "2003";
                break;

            case 3:
                func = "2008";
                break;

            case 4:
                func = "2008 R2";
                break;

            case 5:
                func = "2012";
                break;

            case 6:
                func = "2012 R2";
                break;

            case 7:
                func = "2016";
                break;

            default:
                func = "Unknown";
                break;
            }

            obj.Properties.Add("functionallevel", func);
        }
Esempio n. 42
0
 protected DomainBasedRow(Domain domain, DataTable table)
 {
     this.domain = domain ?? throw new ArgumentNullException(nameof(domain));
     this.table = table;
     this.Backup(this.table.NewRow());
 }
Esempio n. 43
0
        private static void Main(string[] args)
        {
            DateTime grouper2StartTime = DateTime.Now;

            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser();
            ValueArgument <string> htmlArg             = new ValueArgument <string>('f', "html", "Path for html output file.");
            SwitchArgument         debugArg            = new SwitchArgument('v', "verbose", "Enables debug mode. Probably quite noisy and rarely necessary. Will also show you the names of any categories of policies" +
                                                                            " that Grouper saw but didn't have any means of processing. I eagerly await your pull request.", false);
            SwitchArgument offlineArg = new SwitchArgument('o', "offline",
                                                           "Disables checks that require LDAP comms with a DC or SMB comms with file shares found in policy settings. Requires that you define a value for -s.",
                                                           false);
            ValueArgument <string> sysvolArg =
                new ValueArgument <string>('s', "sysvol", "Set the path to a domain SYSVOL directory.");
            ValueArgument <int> intlevArg = new ValueArgument <int>('i', "interestlevel",
                                                                    "The minimum interest level to display. i.e. findings with an interest level lower than x will not be seen in output. Defaults to 1, i.e. show " +
                                                                    "everything except some extremely dull defaults. If you want to see those too, do -i 0.");
            ValueArgument <int>    threadsArg = new ValueArgument <int>('t', "threads", "Max number of threads. Defaults to 10.");
            ValueArgument <string> domainArg  =
                new ValueArgument <string>('d', "domain", "Domain to query for Group Policy Goodies.");
            ValueArgument <string> passwordArg = new ValueArgument <string>('p', "password", "Password to use for LDAP operations.");
            ValueArgument <string> usernameArg =
                new ValueArgument <string>('u', "username", "Username to use for LDAP operations.");
            SwitchArgument helpArg           = new SwitchArgument('h', "help", "Displays this help.", false);
            SwitchArgument prettyArg         = new SwitchArgument('g', "pretty", "Switches output from the raw Json to a prettier format.", false);
            SwitchArgument noMessArg         = new SwitchArgument('m', "nomess", "Avoids file writes at all costs. May find less stuff.", false);
            SwitchArgument currentPolOnlyArg = new SwitchArgument('c', "currentonly", "Only checks current policies, ignoring stuff in those " +
                                                                  "Policies_NTFRS_* directories that result from replication failures.", false);
            SwitchArgument noGrepScriptsArg = new SwitchArgument('n', "nogrepscripts", "Don't grep through the files in the \"Scripts\" subdirectory", false);

            parser.Arguments.Add(usernameArg);
            parser.Arguments.Add(passwordArg);
            parser.Arguments.Add(debugArg);
            parser.Arguments.Add(intlevArg);
            parser.Arguments.Add(sysvolArg);
            parser.Arguments.Add(offlineArg);
            parser.Arguments.Add(threadsArg);
            parser.Arguments.Add(helpArg);
            parser.Arguments.Add(prettyArg);
            parser.Arguments.Add(noMessArg);
            parser.Arguments.Add(currentPolOnlyArg);
            parser.Arguments.Add(noGrepScriptsArg);
            parser.Arguments.Add(domainArg);
            parser.Arguments.Add(htmlArg);

            // set a few defaults
            string sysvolDir = "";

            GlobalVar.OnlineChecks = true;
            int  maxThreads   = 10;
            bool prettyOutput = false;

            GlobalVar.NoMess = false;
            bool   noNtfrs           = false;
            bool   noGrepScripts     = false;
            string userDefinedDomain = "";
            bool   htmlOut           = false;
            string htmlOutPath       = "";

            try
            {
                parser.ParseCommandLine(args);
                if (helpArg.Parsed)
                {
                    foreach (Argument arg in parser.Arguments)
                    {
                        Console.Error.Write("-");
                        Console.Error.Write(arg.ShortName);
                        Console.Error.Write(" " + arg.LongName);
                        Console.Error.WriteLine(" - " + arg.Description);
                    }

                    Environment.Exit(0);
                }
                if (offlineArg.Parsed && offlineArg.Value && sysvolArg.Parsed)
                {
                    // args config for valid offline run.
                    GlobalVar.OnlineChecks = false;
                    sysvolDir = sysvolArg.Value;
                }

                if (offlineArg.Parsed && offlineArg.Value && !sysvolArg.Parsed)
                {
                    // handle someone trying to run in offline mode without giving a value for sysvol
                    Console.Error.WriteLine(
                        "\nOffline mode requires you to provide a value for -s, the path where Grouper2 can find the domain SYSVOL share, or a copy of it at least.");
                    Environment.Exit(1);
                }

                if (intlevArg.Parsed)
                {
                    // handle interest level parsing
                    Console.Error.WriteLine("\nRoger. Everything with an Interest Level lower than " +
                                            intlevArg.Value.ToString() + " is getting thrown on the floor.");
                    GlobalVar.IntLevelToShow = intlevArg.Value;
                }
                else
                {
                    GlobalVar.IntLevelToShow = 1;
                }

                if (htmlArg.Parsed)
                {
                    htmlOut     = true;
                    htmlOutPath = htmlArg.Value;
                }
                if (debugArg.Parsed)
                {
                    Console.Error.WriteLine("\nVerbose debug mode enabled. Hope you like yellow.");
                    GlobalVar.DebugMode = true;
                }

                if (threadsArg.Parsed)
                {
                    Console.Error.WriteLine("\nMaximum threads set to: " + threadsArg.Value);
                    maxThreads = threadsArg.Value;
                }

                if (sysvolArg.Parsed)
                {
                    Console.Error.WriteLine("\nYou specified that I should assume SYSVOL is here: " + sysvolArg.Value);
                    sysvolDir = sysvolArg.Value;
                }

                if (prettyArg.Parsed)
                {
                    Console.Error.WriteLine("\nSwitching output to pretty mode. Nice.");
                    prettyOutput = true;
                }

                if (noMessArg.Parsed)
                {
                    Console.Error.WriteLine("\nNo Mess mode enabled. Good for OPSEC, maybe bad for finding all the vulns? All \"Directory Is Writable\" checks will return false.");

                    GlobalVar.NoMess = true;
                }

                if (currentPolOnlyArg.Parsed)
                {
                    Console.Error.WriteLine("\nOnly looking at current policies and scripts, not checking any of those weird old NTFRS dirs.");
                    noNtfrs = true;
                }

                if (domainArg.Parsed)
                {
                    Console.Error.Write("\nYou told me to talk to domain " + domainArg.Value + " so I'm gonna do that.");
                    if (!(usernameArg.Parsed) || !(passwordArg.Parsed))
                    {
                        Console.Error.Write("\nIf you specify a domain you need to specify a username and password too using -u and -p.");
                    }

                    userDefinedDomain = domainArg.Value;
                    string[]      splitDomain = userDefinedDomain.Split('.');
                    StringBuilder sb          = new StringBuilder();
                    int           pi          = splitDomain.Length;
                    int           ind         = 1;
                    foreach (string piece in splitDomain)
                    {
                        sb.Append("DC=" + piece);
                        if (pi != ind)
                        {
                            sb.Append(",");
                        }
                        ind++;
                    }

                    GlobalVar.UserDefinedDomain   = userDefinedDomain;
                    GlobalVar.UserDefinedDomainDn = sb.ToString();
                    GlobalVar.UserDefinedPassword = passwordArg.Value;
                    GlobalVar.UserDefinedUsername = usernameArg.Value;
                }

                if (noGrepScriptsArg.Parsed)
                {
                    Console.Error.WriteLine("\nNot gonna look through scripts in SYSVOL for goodies.");
                    noGrepScripts = true;
                }
            }
            catch (CommandLineException e)
            {
                Console.WriteLine(e.Message);
            }

            if (GlobalVar.UserDefinedDomain != null)
            {
                Console.Error.WriteLine("\nRunning as user: "******"\\" + GlobalVar.UserDefinedUsername);
            }
            else
            {
                Console.Error.WriteLine("\nRunning as user: "******"\\" + Environment.UserName);
            }
            Console.Error.WriteLine("\nAll online checks will be performed in the context of this user.");


            if (!prettyOutput)
            {
                Output.PrintBanner();
            }

            // Ask the DC for GPO details
            string currentDomainString = "";

            if (GlobalVar.OnlineChecks)
            {
                if (userDefinedDomain != "")
                {
                    currentDomainString = userDefinedDomain;
                }
                else
                {
                    Console.Error.WriteLine("\nTrying to figure out what AD domain we're working with.");
                    try
                    {
                        currentDomainString = Domain.GetCurrentDomain().ToString();
                    }
                    catch (ActiveDirectoryOperationException e)
                    {
                        Console.Error.WriteLine("\nCouldn't talk to the domain properly. If you're trying to run offline you should use the -o switch. Failing that, try rerunning with -d to specify a domain or -v to get more information about the error.");
                        Utility.Output.DebugWrite(e.ToString());

                        Environment.Exit(1);
                    }
                }

                Console.WriteLine("\nCurrent AD Domain is: " + currentDomainString);

                // if we're online, get a bunch of metadata about the GPOs via LDAP
                JObject domainGpos = new JObject();

                if (GlobalVar.OnlineChecks)
                {
                    domainGpos = GetDomainGpoData.DomainGpoData;
                }

                Console.WriteLine("");

                if (sysvolDir == "")
                {
                    sysvolDir = @"\\" + currentDomainString + @"\sysvol\" + currentDomainString + @"\";
                    Console.Error.WriteLine("Targeting SYSVOL at: " + sysvolDir);
                }
            }
            else if ((GlobalVar.OnlineChecks == false) && sysvolDir.Length > 1)
            {
                Console.Error.WriteLine("\nTargeting SYSVOL at: " + sysvolDir);
            }
            else
            {
                Console.Error.WriteLine("\nSomething went wrong with parsing the path to sysvol and I gave up.");
                Environment.Exit(1);
            }

            // get all the dirs with Policies and scripts in an array.
            string[] sysvolDirs =
                Directory.GetDirectories(sysvolDir);

            Console.Error.WriteLine(
                "\nI found all these directories in SYSVOL...");
            Console.Error.WriteLine("#########################################");
            foreach (string line in sysvolDirs)
            {
                Console.Error.WriteLine(line);
            }
            Console.Error.WriteLine("#########################################");

            List <string> sysvolPolDirs    = new List <string>();
            List <string> sysvolScriptDirs = new List <string>();

            if (noNtfrs)
            {
                Console.Error.WriteLine("... but I'm not going to look in any of them except .\\Policies and .\\Scripts because you told me not to.");
                sysvolPolDirs.Add(sysvolDir + "Policies\\");
                sysvolScriptDirs.Add(sysvolDir + "Scripts\\");
            }
            else
            {
                Console.Error.WriteLine("... and I'm going to find all the goodies I can in all of them.");
                foreach (string dir in sysvolDirs)
                {
                    if (dir.ToLower().Contains("scripts"))
                    {
                        sysvolScriptDirs.Add(dir);
                    }

                    if (dir.ToLower().Contains("policies"))
                    {
                        sysvolPolDirs.Add(dir);
                    }
                }
            }

            // get all the policy dirs
            List <string> gpoPaths = new List <string>();

            foreach (string policyPath in sysvolPolDirs)
            {
                try
                {
                    gpoPaths = Directory.GetDirectories(policyPath).ToList();
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("I had a problem with " + policyPath +
                                            ". I guess you could try to fix it?");
                    Output.DebugWrite(e.ToString());
                }
            }

            JObject gpoPackageData = new JObject();

            // Grab Packages from LDAP
            if (GlobalVar.OnlineChecks)
            {
                gpoPackageData = LDAPstuff.GetGpoPackages(Environment.UserDomainName.ToString());
            }



            // create a JObject to put all our output goodies in.
            JObject grouper2Output = new JObject();
            // so for each uid directory (including ones with that dumb broken domain replication condition)
            // we're going to gather up all our goodies and put them into that dict we just created.
            // Create a TaskScheduler
            LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(maxThreads);
            List <Task> gpoTasks = new List <Task>();

            // create a TaskFactory
            TaskFactory             gpoFactory = new TaskFactory(lcts);
            CancellationTokenSource gpocts     = new CancellationTokenSource();

            Console.Error.WriteLine("\n" + gpoPaths.Count.ToString() + " GPOs to process.");
            Console.Error.WriteLine("\nStarting processing GPOs with " + maxThreads.ToString() + " threads.");

            JObject taskErrors = new JObject();

            // Create a task for each GPO
            foreach (string gpoPath in gpoPaths)
            {
                Task t = gpoFactory.StartNew(() =>
                {
                    try
                    {
                        JObject matchedPackages = new JObject();
                        if (GlobalVar.OnlineChecks)
                        {
                            // figure out the gpo UID from the path so we can see which packages need to be processed here.
                            string[] gpoPathArr      = gpoPath.Split('{');
                            string gpoPathBackString = gpoPathArr[1];
                            string[] gpoPathBackArr  = gpoPathBackString.Split('}');
                            string gpoUid            = gpoPathBackArr[0].ToString().ToLower();

                            // see if we have any appropriate matching packages and construct a little bundle
                            foreach (KeyValuePair <string, JToken> gpoPackage in gpoPackageData)
                            {
                                string packageParentGpoUid = gpoPackage.Value["ParentGPO"].ToString().ToLower()
                                                             .Trim('{', '}');
                                if (packageParentGpoUid == gpoUid)
                                {
                                    JProperty assessedPackage = PackageAssess.AssessPackage(gpoPackage);
                                    if (assessedPackage != null)
                                    {
                                        matchedPackages.Add(assessedPackage);
                                    }
                                }
                            }
                        }


                        JObject gpoFindings = ProcessGpo(gpoPath, matchedPackages);

                        if (gpoFindings != null)
                        {
                            if (gpoFindings.HasValues)
                            {
                                lock (grouper2Output)
                                {
                                    if (!(gpoPath.Contains("NTFRS")))
                                    {
                                        grouper2Output.Add(("Current Policy - " + gpoPath), gpoFindings);
                                    }
                                    else
                                    {
                                        grouper2Output.Add(gpoPath, gpoFindings);
                                    }
                                }
                            }
                        }
                    }

                    catch (Exception e)
                    {
                        taskErrors.Add(gpoPath, e.ToString());
                    }
                }, gpocts.Token);
                gpoTasks.Add(t);
            }

            // put 'em all in a happy little array
            Task[] gpoTaskArray = gpoTasks.ToArray();

            // create a little counter to provide status updates
            int totalGpoTasksCount  = gpoTaskArray.Length;
            int incompleteTaskCount = gpoTaskArray.Length;
            int remainingTaskCount  = gpoTaskArray.Length;

            while (remainingTaskCount > 0)
            {
                Task[] incompleteTasks =
                    Array.FindAll(gpoTaskArray, element => element.Status != TaskStatus.RanToCompletion);
                incompleteTaskCount = incompleteTasks.Length;
                Task[] faultedTasks = Array.FindAll(gpoTaskArray,
                                                    element => element.Status == TaskStatus.Faulted);
                int    faultedTaskCount  = faultedTasks.Length;
                int    completeTaskCount = totalGpoTasksCount - incompleteTaskCount - faultedTaskCount;
                int    percentage        = (int)Math.Round((double)(100 * completeTaskCount) / totalGpoTasksCount);
                string percentageString  = percentage.ToString();
                Console.Error.Write("");

                Console.Error.Write("\r" + completeTaskCount.ToString() + "/" + totalGpoTasksCount.ToString() +
                                    " GPOs processed. " + percentageString + "% complete. ");
                if (faultedTaskCount > 0)
                {
                    Console.Error.Write(faultedTaskCount.ToString() + " GPOs failed to process.");
                }

                remainingTaskCount = incompleteTaskCount - faultedTaskCount;
            }

            // make double sure tasks all finished
            Task.WaitAll(gpoTasks.ToArray());
            gpocts.Dispose();

            // do the script grepping
            if (!(noGrepScripts))
            {
                Console.Error.Write("\n\nProcessing SYSVOL script dirs.\n\n");
                JObject processedScriptDirs = ProcessScripts(sysvolScriptDirs);
                if ((processedScriptDirs != null) && (processedScriptDirs.HasValues))
                {
                    grouper2Output.Add("Scripts", processedScriptDirs);
                }
            }

            Console.Error.WriteLine("Errors in processing GPOs:");
            Console.Error.WriteLine(taskErrors.ToString());

            // Final output is finally happening finally here:

            if (prettyOutput || htmlOut)
            {
                // gotta add a line feed to make sure we're clear to write the nice output.
                Console.Error.WriteLine("\n");

                if (htmlOut)
                {
                    try
                    {
                        // gotta add a line feed to make sure we're clear to write the nice output.

                        Document htmlDoc = new Document();

                        htmlDoc.Children.Add(Output.GetG2BannerDocument());

                        foreach (KeyValuePair <string, JToken> gpo in grouper2Output)
                        {
                            htmlDoc.Children.Add(Output.GetAssessedGpoOutput(gpo));
                        }
                        ConsoleRenderer.RenderDocument(htmlDoc,
                                                       new HtmlRenderTarget(File.Create(htmlOutPath), new UTF8Encoding(false)));
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Console.Error.WriteLine("Tried to write html output file but I'm not allowed.");
                    }
                }

                if (prettyOutput)
                {
                    Document prettyDoc = new Document();

                    prettyDoc.Children.Add(Output.GetG2BannerDocument());

                    foreach (KeyValuePair <string, JToken> gpo in grouper2Output)
                    {
                        prettyDoc.Children.Add(Output.GetAssessedGpoOutput(gpo));
                    }
                    ConsoleRenderer.RenderDocument(prettyDoc);
                }
            }
            else
            {
                Console.WriteLine(grouper2Output);
                Console.Error.WriteLine("If you find yourself thinking 'wtf this is very ugly and hard to read', consider trying the -g argument.");
            }


            // get the time it took to do the thing and give to user
            DateTime grouper2EndTime       = DateTime.Now;
            TimeSpan grouper2RunTime       = grouper2EndTime.Subtract(grouper2StartTime);
            string   grouper2RunTimeString =
                $"{grouper2RunTime.Hours}:{grouper2RunTime.Minutes}:{grouper2RunTime.Seconds}:{grouper2RunTime.Milliseconds}";

            Console.WriteLine("Grouper2 took " + grouper2RunTimeString + " to run.");

            if (GlobalVar.CleanupList != null)
            {
                List <string> cleanupList = Util.DedupeList(GlobalVar.CleanupList);
                if (cleanupList.Count >= 1)
                {
                    Console.WriteLine("\n\nGrouper2 tried to create these files. It probably failed, but just in case it didn't, you might want to check and clean them up.\n");
                    foreach (string path in cleanupList)
                    {
                        Console.WriteLine(path);
                    }
                }
            }
            // FINISHED!
            bool isDebuggerAttached = System.Diagnostics.Debugger.IsAttached;

            if (isDebuggerAttached)
            {
                Console.Error.WriteLine("Press any key to Exit");
                Console.ReadKey();
            }
            Environment.Exit(0);
        }
Esempio n. 44
0
        /// <summary>
        /// Get an iFolder User Details Object
        /// </summary>
        /// <param name="member">The Member Object</param>
        /// <param name="collection">The Collection Object</param>
        /// <param name="domain">The Domain Object</param>
        /// <returns>An iFolderUser Object</returns>
        protected iFolderUserDetails(Member member, Collection collection, Domain domain)
            : base(member, collection, domain)
        {
            if (member.HomeServer != null)
            {
                this.DetailHomeServer = (member.HomeServer.Name == null) ? string.Empty : member.HomeServer.Name;
            }
            else
            {
                this.DetailHomeServer = string.Empty;
            }

            if (member.NewHomeServer != null)
            {
                HostNode newHomeNode = HostNode.GetHostByID(domain.ID, member.NewHomeServer);
                if (newHomeNode != null)
                {
                    this.DetailNewHomeServer = (newHomeNode.Name == null) ? string.Empty : newHomeNode.Name;
                }
                else
                {
                    this.DetailNewHomeServer = string.Empty;
                }
            }
            else
            {
                this.DetailNewHomeServer = string.Empty;
            }

            int state = member.UserMoveState;

            switch (state)
            {
            case (int)Member.userMoveStates.PreProcessingFailed:
                DetailDataMoveStatus = "NOTELIGIBLE";
                DataMovePercentage   = 0;
                break;

            case (int)Member.userMoveStates.Nousermove:
            case (int)Member.userMoveStates.Initialized:
                DetailDataMoveStatus     = "Initializing";
                DetailDataMovePercentage = 0;
                break;

            case (int)Member.userMoveStates.UserDisabled:
                DetailDataMoveStatus     = "Initialized";
                DetailDataMovePercentage = 5;
                break;

            case (int)Member.userMoveStates.DataMoveStarted:
                DetailDataMoveStatus     = "Moving iFolders";
                DetailDataMovePercentage = 10;
                break;

            case (int)Member.userMoveStates.Reprovision:
                DetailDataMoveStatus     = "Resetting Home";
                DetailDataMovePercentage = 10;
                break;

            case (int)Member.userMoveStates.MoveCompleted:
                DetailDataMoveStatus     = "Finalizing";
                DetailDataMovePercentage = 15;
                break;

            default:
                DetailDataMovePercentage = 0;
                DetailDataMoveStatus     = "Initializing";
                break;
            }
            if (state < (int)Member.userMoveStates.DataMoveStarted)
            {
                DetailDataMovePercentage += 0;
            }
            else if (state > (int)Member.userMoveStates.DataMoveStarted)
            {
                DetailDataMovePercentage += 80;
            }
            else
            {
                Store stored           = Store.GetStore();
                long  SpaceUsed        = 0;
                long  DataTransferred  = 1;
                int   iFolderMoveState = 0;

                // From catalog, get the total size of the collections owned by this user.
                // Then, check which iFolders are present on local machine, those which are not present are moved, minus them
                long     TotalSpaceUsed     = Catalog.GetSpaceUsedByOwnerID(member.UserID);
                HostNode LocalHostNode      = HostNode.GetLocalHost();
                bool     LocalHostIsNewHome = false;
                bool     LocalHostIsOldHome = false;
                bool     ValidLocalHost     = (LocalHostNode != null && !String.IsNullOrEmpty(LocalHostNode.Name));

                if (ValidLocalHost && !String.IsNullOrEmpty(this.HomeServer) && String.Equals(this.HomeServer, LocalHostNode.Name))
                {
                    LocalHostIsOldHome = true;
                }

                if (ValidLocalHost && !String.IsNullOrEmpty(this.DetailNewHomeServer) && String.Equals(this.DetailNewHomeServer, LocalHostNode.Name))
                {
                    LocalHostIsNewHome = true;
                }

                // If localhost is where user is moving, then start with 0 and add all collections in local store as moved ones
                // If localhost is older home, then start with total data size and subtract collections which are not in local store
                DataTransferred = LocalHostIsNewHome ? 0 : (LocalHostIsOldHome ? TotalSpaceUsed : 0);


                ICSList collectionList = stored.GetCollectionsByOwner(member.UserID, domain.ID);
                foreach (ShallowNode sn in collectionList)
                {
                    Collection iFolderCol = new Collection(stored, sn);
                    //SpaceUsed += iFolderCol.StorageSize;
                    iFolderMoveState = member.iFolderMoveState(domain.ID, false, iFolderCol.ID, 0, 0);
                    if (iFolderMoveState > 1)
                    {
                        // This is almost non-reachable code. because when iFolderMoveState becomes 2, it means collection is
                        // moved and in that case, the collection will not be present in local store, so store.getco..Owner
                        // will not return the collection's ID. should not we remove this true codepath????
                        //it comes momentarily here only once..
                        DataTransferred += iFolderCol.StorageSize;
                    }
                    else
                    {
                        DataTransferred = LocalHostIsNewHome ? (DataTransferred + iFolderCol.StorageSize /* local server is new home for the user*/) : (DataTransferred - iFolderCol.StorageSize /* user is getting moved away from local server*/);
                    }
                }
                if (TotalSpaceUsed != 0)
                {
                    log.Debug("iFolderUserDetails: After total calculation, now size of data that already moved is {0} and total space used by user/allcolls is {1}", DataTransferred, TotalSpaceUsed);
                    DetailDataMovePercentage += (int)((80 * DataTransferred) / TotalSpaceUsed);
                    log.Debug("iFolderUserDetails: DataMovePercentage after calculation is :" + DetailDataMovePercentage);
                }
                else
                {
                    DetailDataMovePercentage += 80;
                }
            }
            if (member.NewHomeServer != null)
            {
                HostNode newHomeNode = HostNode.GetHostByID(domain.ID, member.NewHomeServer);
                if (newHomeNode != null)
                {
                    this.DetailNewHomeServer = (newHomeNode.Name == null) ? string.Empty : newHomeNode.Name;
                }
                else
                {
                    this.DetailNewHomeServer = string.Empty;
                }
            }
            else
            {
                this.DetailNewHomeServer = string.Empty;
            }

            // sync interval
            this.SyncIntervalEffective = Simias.Policy.SyncInterval.Get(collection).Interval;

            // last login
            Member   domainMember = domain.GetMemberByID(this.ID);
            Property p            = domainMember.Properties.GetSingleProperty(PropertyTags.LastLoginTime);

            if (p != null)
            {
                this.LastLogin = (DateTime)p.Value;
            }

            // Get the DN property for the member if it exists.
            Property property = domainMember.Properties.GetSingleProperty("DN");

            this.LdapContext = (property != null) ? property.ToString() : String.Empty;

            // Get the GroupType property for the member if it exists.
            Property Groupproperty = domainMember.Properties.GetSingleProperty("GroupType");

            if (null == Groupproperty)
            {
                this.MemberType = 0;
                Property GOMproperty = domainMember.Properties.GetSingleProperty("UserGroups");
                this.GroupOrMemberList = (GOMproperty != null) ? GOMproperty.ToString() : String.Empty;
            }
            else
            {
                if (String.Compare(Groupproperty.ToString().ToLower(), "global") == 0)
                {
                    this.MemberType = 1;
                }
                else
                {
                    this.MemberType = 2;
                }
                {
                    // This braces is for adding members into group object and vice-versa
                    string          FullMembersList = "";
                    MultiValuedList mvl             = member.Properties.GetProperties("MembersList");
                    if (mvl != null && mvl.Count > 0)
                    {
                        foreach (Property prop in mvl)
                        {
                            if (prop != null)
                            {
                                FullMembersList += prop.Value as string;
                                FullMembersList += "; ";
                            }
                        }
                    }
                    this.GroupOrMemberList = FullMembersList;
                    this.GroupDiskQuota    = member.AggregateDiskQuota;
                    this.SpaceUsedByGroup  = iFolderUser.SpaceUsedByGroup(member.UserID);
                }
            }

            // Get the number of iFolders owned and shared by the user.
            CatalogEntry[] catalogEntries;
            catalogEntries = Catalog.GetAllEntriesByUserID(this.ID);
            foreach (CatalogEntry ce in catalogEntries)
            {
                if (ce.OwnerID == this.ID)
                {
                    ++OwnediFolderCount;
                }
                else
                {
                    ++SharediFolderCount;
                }
            }
        }
Esempio n. 45
0
 public IPAddressResourceRecord(Domain domain, IPAddress ip, TimeSpan ttl = default(TimeSpan)) :
     base(Create(domain, ip, ttl))
 {
     IPAddress = ip;
 }
Esempio n. 46
0
        /// <inheritdoc />
        public bool Equals([AllowNull] AngularAxis other)
        {
            if (other == null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Equals(Range, other.Range) ||
                     Range != null && other.Range != null &&
                     Range.SequenceEqual(other.Range)
                     ) &&
                 (
                     Equals(Domain, other.Domain) ||
                     Domain != null && other.Domain != null &&
                     Domain.SequenceEqual(other.Domain)
                 ) &&
                 (
                     ShowLine == other.ShowLine ||
                     ShowLine != null &&
                     ShowLine.Equals(other.ShowLine)
                 ) &&
                 (
                     ShowTickLabels == other.ShowTickLabels ||
                     ShowTickLabels != null &&
                     ShowTickLabels.Equals(other.ShowTickLabels)
                 ) &&
                 (
                     TickOrientation == other.TickOrientation ||
                     TickOrientation != null &&
                     TickOrientation.Equals(other.TickOrientation)
                 ) &&
                 (
                     TickleN == other.TickleN ||
                     TickleN != null &&
                     TickleN.Equals(other.TickleN)
                 ) &&
                 (
                     TickColor == other.TickColor ||
                     TickColor != null &&
                     TickColor.Equals(other.TickColor)
                 ) &&
                 (
                     TickSuffix == other.TickSuffix ||
                     TickSuffix != null &&
                     TickSuffix.Equals(other.TickSuffix)
                 ) &&
                 (
                     EndPadding == other.EndPadding ||
                     EndPadding != null &&
                     EndPadding.Equals(other.EndPadding)
                 ) &&
                 (
                     Visible == other.Visible ||
                     Visible != null &&
                     Visible.Equals(other.Visible)
                 ));
        }
Esempio n. 47
0
 public void Setup()
 {
     this.container = new Container();
     this.domain    = this.container.CreateDomain("Customers");
     this.item      = this.domain.CreateItem(1);
 }
Esempio n. 48
0
 public EnumType_v1(int size, Types.Domain domain, string p)
 {
     this.Size   = size;
     this.Domain = domain;
     this.Name   = p;
 }
Esempio n. 49
0
 public PointerResourceRecord(IResourceRecord record, byte[] message, int dataOffset)
     : base(record)
 {
     PointerDomainName = Domain.FromArray(message, dataOffset);
 }
Esempio n. 50
0
 public object Clone()
 {
     return(new Variable(Name, (ghost.Domain)Domain.Clone(), Race, GetValue()));
 }
Esempio n. 51
0
        public (double avg, double dev) Calculate(IEnumerable <OptimizationSolution> solutions, double stepSize, Domain problemDomain)
        {
            OptimizationSolution[] solutionArray = solutions.ToArray();
            double[] gradients = new double[solutionArray.Length - 1];

            double fMin = double.PositiveInfinity;
            double fMax = double.NegativeInfinity;

            for (int i = 1; i < solutionArray.Length; i++)
            {
                fMin = Math.Min(fMin, solutionArray[i].Fitness.Value);
                fMax = Math.Max(fMax, solutionArray[i].Fitness.Value);
            }

            double fRange = fMax - fMin;

            double domSum = 0;

            for (int i = 0; i < problemDomain.Dimension; i++)
            {
                domSum += problemDomain[i].Range;
            }

            double gradSum = 0;
            //calculate gradients
            double distTerm = stepSize / domSum;

            for (int i = 1; i < solutionArray.Length; i++)
            {
                OptimizationSolution a = solutionArray[i - 1];
                OptimizationSolution b = solutionArray[i];

                double fitTerm = (b.Fitness.Value - a.Fitness.Value) / fRange;

                gradients[i - 1] = fitTerm / distTerm;

                gradSum += Math.Abs(gradients[i - 1]);
            }

            double avg = gradSum / solutionArray.Length;

            double devSum = 0;

            for (int i = 0; i < gradients.Length; i++)
            {
                devSum += Math.Pow(avg - Math.Abs(gradients[i]), 2);
            }

            double dev = Math.Sqrt(devSum / (solutionArray.Length - 2));

            return(avg, dev);
        }
Esempio n. 52
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometry   = new List <IGH_GeometricGoo>();
            var domainType = 0;
            var cellSize   = 1.0;
            var z0         = false;
            var centerXY   = true;
            var xyScale    = 1.2;
            var xyOffset   = 10.0;
            var zScale     = 2.0;
            var square     = true;
            var plane      = new Plane();

            if (!DA.GetDataList(0, geometry))
            {
                return;
            }

            DA.GetData(1, ref domainType);

            if (!DA.GetData(2, ref cellSize))
            {
                return;
            }

            if (cellSize <= 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Cell Size has to be larger that 0. Given Cell Size was: {cellSize}");
            }

            DA.GetData(3, ref z0);
            DA.GetData(4, ref centerXY);
            DA.GetData(5, ref square);
            DA.GetData(6, ref xyScale);
            DA.GetData(7, ref xyOffset);
            DA.GetData(8, ref zScale);
            DA.GetData(9, ref plane);

            // Create Bounding Box
            var bbs = geometry.Select(element => element.Boundingbox).ToList();

            var boundingBox = Domain.GetMultiBoundingBox(bbs, cellSize, z0, centerXY, xyScale, xyOffset, zScale, square);

            if (domainType == 1)
            {
                boundingBox = Domain.Create2DDomain(boundingBox, plane, cellSize);
            }

            // Construct Surface Dict

            var surfaces = GetSurfaces(geometry, cellSize);

            var refinementRegions = GetRefinementRegions(geometry, cellSize);

            var locationInMesh = Domain.GetLocationInMesh(new Box(boundingBox));
            var cellEstimation = Convert.ToInt32(Domain.EstimateCellCount(geometry, cellSize, xyScale, zScale));
            var outputs        = new Inputs
            {
                Mesh = new CFDMesh
                {
                    BaseMesh = new BaseMesh
                    {
                        Type        = "simpleBox",
                        CellSize    = cellSize,
                        BoundingBox = new Dictionary <string, object>
                        {
                            {
                                "min", new List <double>
                                {
                                    boundingBox.Min.X, boundingBox.Min.Y, boundingBox.Min.Z
                                }
                            },
                            {
                                "max", new List <double>
                                {
                                    boundingBox.Max.X, boundingBox.Max.Y, boundingBox.Max.Z
                                }
                            }
                        },
                        Parameters = new Dictionary <string, string>
                        {
                            { "square", Convert.ToString(square) },
                            { "z0", Convert.ToString(z0) }
                        }
                    },
                    SnappyHexMesh = new SnappyHexMesh
                    {
                        Surfaces  = surfaces,
                        Overrides = new SnappyHexMeshOverrides
                        {
                            CastellatedMeshControls = new CastellatedMeshControls
                            {
                                LocationInMesh = new List <double>
                                {
                                    locationInMesh.X, locationInMesh.Y, locationInMesh.Z
                                }
                            }
                        },
                        RefinementRegions = refinementRegions
                    },
                    CellEstimate = cellEstimation
                }
            };

            DA.SetData(0, outputs.ToJson());
            DA.SetData(1, GetInfoText(cellEstimation, cellSize, surfaces.Keys.Select(key => surfaces[key].Level.Min)));
            DA.SetData(2, boundingBox);
            DA.SetDataList(3, geometry);
        }
        private Task <Domain> BuildDomainAsync(DomainUpgradeMode upgradeMode, NamingRules namingRules, Type sampleType)
        {
            var configuration = BuildDomainConfiguration(upgradeMode, namingRules, sampleType);

            return(Domain.BuildAsync(configuration));
        }
Esempio n. 54
0
 public PointerResourceRecord(IPAddress ip, Domain pointer, TimeSpan ttl = default(TimeSpan)) :
     base(new ResourceRecord(Domain.PointerName(ip), pointer.ToArray(), DnsRecordType.PTR, DnsRecordClass.IN, ttl))
 {
     PointerDomainName = pointer;
 }
Esempio n. 55
0
        public List <CodeFile> GenerateComponents(Domain domain)
        {
            Util.RegisterHelpers(domain.TypeProvider);
            var files = new List <CodeFile>();

            var all = new CodeFile {
                Name = "all-types.tsx", Contents = GenerateAllPage(domain)
            };

            files.Add(all);

            var regUserHome = new CodeFile {
                Name = "RegularUserHome.tsx", Contents = GenerateRegularUserHomepage(domain)
            };

            files.Add(regUserHome);

            foreach (var type in domain.FilteredTypes.OrderBy(t => t.Name))
            {
                if (type.GenerateUI)
                {
                    var namestart = Util.TypescriptFileName(type.Name);
                    var path      = GetRelativePathFromTypeName(type.Name);
                    var adapter   = new ClientApiAdapter(type, domain);

                    files.Add(new CodeFile {
                        Name = namestart + "Select.tsx", Contents = GenerateFromTemplate(adapter, TemplateNames.ReactSelectControl), RelativePath = path, Template = TemplateNames.ReactSelectControl
                    });
                    files.Add(new CodeFile {
                        Name = namestart + "Component.tsx", Contents = GenerateFromTemplate(adapter, TemplateNames.ReactComponent), RelativePath = path, Template = TemplateNames.ReactComponent
                    });

                    if (adapter.HasDetails)
                    {
                        var detailAdapter = new ClientDetailAdapter(type, domain);
                        files.Add(new CodeFile {
                            Name = namestart + "Detail.tsx", Contents = GenerateFromTemplate(detailAdapter, TemplateNames.ReactDetailPage), RelativePath = path, Template = TemplateNames.ReactDetailPage
                        });
                    }

                    foreach (var operation in adapter.ApiOperations.Where(op => op.ChangesData && op.GenerateUI))
                    {
                        var changeDataAdapter = new ClientApiInsertUpdateAdapter(type, domain, operation);
                        files.Add(new CodeFile {
                            Name = namestart + operation.FriendlyName + ".tsx", Contents = GenerateFromTemplate(changeDataAdapter, TemplateNames.ReactAddEditPage), RelativePath = path, Template = TemplateNames.ReactAddEditPage
                        });
                        files.Add(new CodeFile {
                            Name = namestart + operation.FriendlyName + "Rendering.tsx", Contents = GenerateFromTemplate(changeDataAdapter, TemplateNames.ReactAddEditPageRendering), RelativePath = path, Template = TemplateNames.ReactAddEditPageRendering
                        });
                    }

                    if (adapter.Operations.Any(op => op.ChangesData && op.GenerateUI))
                    {
                        files.Add(new CodeFile {
                            Name = namestart + "Validate.tsx", Contents = GenerateFromTemplate(adapter, TemplateNames.ModelValidator), RelativePath = path, Template = TemplateNames.ModelValidator
                        });
                    }

                    if (adapter.CanDelete)
                    {
                        files.Add(new CodeFile {
                            Name = namestart + "ConfirmDelete.tsx", Contents = GenerateFromTemplate(adapter, TemplateNames.ReactConfirmDeletePage), RelativePath = path, Template = TemplateNames.ReactConfirmDeletePage
                        });
                    }
                }
            }

            // build 'list' UIs from return types
            foreach (var rt in domain.Operations.Where(o => o.GenerateUI && o.RelatedType?.GenerateUI == true && (o.Returns != null && o.Returns.ReturnType == ReturnType.ApplicationType || o.Returns != null && o.Returns.ReturnType == ReturnType.CustomType))
                     .Select(o => new { o.Returns.SimpleReturnType, RelatedType = o.Returns.SimpleReturnType is ApplicationType ? o.RelatedType : ((ResultType)o.Returns.SimpleReturnType).RelatedType }) // get the related type from the result type if it is a custom type, or from the operation if the operation returns an application type - allows OpenApi operations to re-use types across application types.
                     .Distinct()
                     .OrderBy(rt => rt.RelatedType.Name))
            {
                if (rt.RelatedType == null || domain.FilteredTypes.Contains(rt.RelatedType))
                {
                    var listAdapter = new ListViewAdapter(rt.SimpleReturnType, domain, rt.RelatedType);
                    var listPath    = GetRelativePathFromTypeName(rt.RelatedType.Name) + "list\\";
                    var nameStart   = Util.TypescriptFileName(rt.SimpleReturnType.Name);

                    files.Add(new CodeFile {
                        Name = nameStart + "List.tsx", Contents = GenerateFromTemplate(listAdapter, TemplateNames.ReactListPage), RelativePath = listPath, Template = TemplateNames.ReactListPage
                    });
                    files.Add(new CodeFile {
                        Name = nameStart + "Header.tsx", Contents = GenerateFromTemplate(listAdapter, TemplateNames.ReactListHeader), RelativePath = listPath, Template = TemplateNames.ReactListHeader
                    });
                    files.Add(new CodeFile {
                        Name = nameStart + "Row.tsx", Contents = GenerateFromTemplate(listAdapter, TemplateNames.ReactListRow), RelativePath = listPath, Template = TemplateNames.ReactListRow
                    });
                    files.Add(new CodeFile {
                        Name = nameStart + "ListRendering.tsx", Contents = GenerateFromTemplate(listAdapter, TemplateNames.ReactListRendering), RelativePath = listPath, Template = TemplateNames.ReactListRendering
                    });
                }
            }

            foreach (var srchOp in domain.Operations.Where(o => o.RelatedType != null).Select(o => new ClientApiOperationAdapter(o, domain, o.RelatedType)).Where(o => o.RelatedType?.GenerateUI == true && o.IsSearch))
            {
                if (srchOp.RelatedType != null && domain.FilteredTypes.Contains(srchOp.RelatedType))
                {
                    var search = new CodeFile {
                        Name = Util.TypescriptFileName(srchOp.Name) + ".tsx", Contents = GenerateFromTemplate(srchOp, TemplateNames.ReactSearchControl), RelativePath = GetRelativePathFromTypeName(srchOp.RelatedType.Name), Template = TemplateNames.ReactSearchControl
                    };
                    files.Add(search);
                }
            }

            var appImports = new CodeFile {
                Name = "../App.tsx", Contents = GenerateFromTemplate(new DomainAdapter(domain), "AppImports"), IsFragment = true
            };

            files.Add(appImports);

            var appRoutes = new CodeFile {
                Name = "../App.tsx", Contents = GenerateFromTemplate(new DomainAdapter(domain), "AppRoutes"), IsFragment = true
            };

            files.Add(appRoutes);

            return(files);
        }
Esempio n. 56
0
        /// <summary>
        /// retrieve an user documents folder; also validates the user credentials to prevent unauthorized access to this folder
        /// </summary>
        /// <param name="userDomain"></param>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        /// <returns>documents directory</returns>
        public static string GetUserDocumentsFolder(
            string userDomain,
            string userName,
            string userPassword)
        {
            var token = IntPtr.Zero;

            try
            {
                // logon the user, domain (if defined) or local otherwise
                // myrtille must be running on a machine which is part of the domain for it to work
                if (LogonUser(userName, string.IsNullOrEmpty(userDomain) ? Environment.MachineName : userDomain, userPassword, string.IsNullOrEmpty(userDomain) ? (int)LogonType.LOGON32_LOGON_INTERACTIVE : (int)LogonType.LOGON32_LOGON_NETWORK, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, ref token))
                {
                    string serverName = null;
                    if (!string.IsNullOrEmpty(userDomain))
                    {
                        var context    = new DirectoryContext(DirectoryContextType.Domain, userDomain, userName, userPassword);
                        var controller = Domain.GetDomain(context).FindDomainController();
                        serverName = controller.Name;
                    }

                    IntPtr bufPtr;
                    if (NetUserGetInfo(serverName, userName, 4, out bufPtr) == NET_API_STATUS.NERR_Success)
                    {
                        var userInfo = new USER_INFO_4();
                        userInfo = (USER_INFO_4)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_4));

                        var profileInfo = new ProfileInfo
                        {
                            dwSize        = Marshal.SizeOf(typeof(ProfileInfo)),
                            dwFlags       = (int)ProfileInfoFlags.PI_NOUI,
                            lpServerName  = string.IsNullOrEmpty(userDomain) ? Environment.MachineName : serverName.Split(new[] { "." }, StringSplitOptions.None)[0],
                            lpUserName    = string.IsNullOrEmpty(userDomain) ? userName : string.Format(@"{0}\{1}", userDomain, userName),
                            lpProfilePath = userInfo.usri4_profile
                        };

                        // load the user profile (roaming if a domain is defined, local otherwise), in order to have it mounted into the registry hive (HKEY_CURRENT_USER)
                        // the user must have logged on at least once for windows to create its profile (this is forcibly done as myrtille requires an active remote session for the user to enable file transfer)
                        if (LoadUserProfile(token, ref profileInfo))
                        {
                            if (profileInfo.hProfile != IntPtr.Zero)
                            {
                                try
                                {
                                    // retrieve the user documents folder path, possibly redirected by a GPO to a network share (read/write accessible to domain users)
                                    // ensure the user doesn't have exclusive rights on it (otherwise myrtille won't be able to access it)
                                    IntPtr outPath;
                                    var    result = SHGetKnownFolderPath(KNOWNFOLDER_GUID_DOCUMENTS, (uint)KnownFolderFlags.DontVerify, token, out outPath);
                                    if (result == 0)
                                    {
                                        return(Marshal.PtrToStringUni(outPath));
                                    }
                                }
                                finally
                                {
                                    UnloadUserProfile(token, profileInfo.hProfile);
                                }
                            }
                        }
                    }
                }
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to retrieve user {0} documents folder ({1})", userName, exc);
                throw;
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
            }
        }
Esempio n. 57
0
 private string GenerateRegularUserHomepage(Domain domain)
 {
     return(GenerateFromTemplate(new DomainApiAdapter(domain), "ReactRegularUserHome"));
 }
        private Domain BuildDomain(DomainUpgradeMode upgradeMode, NamingRules namingRules, Type sampleType)
        {
            var configuration = BuildDomainConfiguration(upgradeMode, namingRules, sampleType);

            return(Domain.Build(configuration));
        }
Esempio n. 59
0
        public void DomainGlobalTest()
        {
            string       dmName    = "testDomainInCS";
            string       csName    = "domainCS";
            string       clName    = "domainCL";
            string       groupName = config.conf.Groups[0].GroupName;
            BsonDocument options   = new BsonDocument();
            BsonArray    arr       = new BsonArray();

            arr.Add(groupName);
            options.Add(SequoiadbConstants.FIELD_GROUPS, arr);
            Domain       dm     = null;
            DBCursor     cur    = null;
            BsonDocument record = null;

            /// IsDomainExist
            bool flag = sdb.IsDomainExist(dmName);

            Assert.IsFalse(flag);

            /// getDomain
            try
            {
                dm = sdb.GetDomain(dmName);
            }
            catch (BaseException e)
            {
                Assert.IsTrue(e.ErrorType.Equals("SDB_CAT_DOMAIN_NOT_EXIST"));
            }

            /// createDomain
            dm = null;
            dm = sdb.CreateDomain(dmName, options);
            Assert.IsNotNull(dm);

            /// IsDomainExist
            flag = false;
            flag = sdb.IsDomainExist(dmName);
            Assert.IsTrue(flag);

            /// getDomain
            dm = null;
            dm = sdb.GetDomain(dmName);
            Assert.IsNotNull(dm);

            /// listDomains
            cur = sdb.ListDomains(null, null, null, null);
            Assert.IsNotNull(cur);
            record = cur.Next();
            Assert.IsNotNull(record);

            /// getName
            string name = dm.Name;

            Assert.IsTrue(name.Equals(dmName));

            // create cs
            BsonDocument opts1 = new BsonDocument();

            opts1.Add("Domain", dmName);
            CollectionSpace cs = sdb.CreateCollectionSpace(csName, opts1);
            // create cl
            BsonDocument opts2 = new BsonDocument();

            //BsonDocument key = new BsonDocument();
            //key.Add("a", 1);
            opts2.Add("ShardingKey", new BsonDocument("a", 1));
            opts2.Add("ShardingType", "hash");
            opts2.Add("AutoSplit", true);
            DBCollection cl = cs.CreateCollection(clName, opts2);

            /// listCS
            cur = dm.ListCS();
            Assert.IsNotNull(cur);
            record = cur.Next();
            Assert.IsNotNull(record);

            /// listCL
            cur = dm.ListCL();
            Assert.IsNotNull(cur);
            record = cur.Next();
            Assert.IsNotNull(record);

            // dropCS
            sdb.DropCollectionSpace(csName);

            /// alter
            /// TODO: alter should be verified
            BsonDocument opts3 = new BsonDocument();
            BsonArray    arr2  = new BsonArray();

            opts3.Add("Groups", arr2);
            opts3.Add("AutoSplit", false);
            dm.Alter(opts3);

            /// listDomains
            cur = sdb.ListDomains(null, null, null, null);
            Assert.IsNotNull(cur);
            record = cur.Next();
            Assert.IsNotNull(record);

            /// dropDomain
            sdb.DropDomain(dmName);

            /// listDomains
            cur = sdb.ListDomains(null, null, null, null);
            Assert.IsNotNull(cur);
            record = cur.Next();
            Assert.IsNull(record);
        }
Esempio n. 60
0
 private string GenerateAllPage(Domain domain)
 {
     return(GenerateFromTemplate(new DomainApiAdapter(domain), "ReactListAllEntitiesPage"));
 }