Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Util u = new Util();

            Console.WriteLine(u.x);

            Thread t = new Thread(new ThreadStart(u.Incrementar));
            t.Start();
            Thread.Sleep(500);

            t = new Thread(new ThreadStart(u.Atribuir));
            t.Start();
            Thread.Sleep(500);

            t = new Thread(new ThreadStart(u.AtribuirSe));
            t.Start();
            Thread.Sleep(500);

            t = new Thread(new ThreadStart(u.Decrementar));
            t.Start();
            Thread.Sleep(500);

            t = new Thread(new ThreadStart(u.Somar));
            t.Start();
            Thread.Sleep(500);

            Console.WriteLine(u.x);

            Console.ReadKey();
        }
Ejemplo n.º 2
0
 public void ZedGraphWrapper_DoubleClick(Util.Variable.DataPoint point)
 {
     if (captureSwitch)
     {
         AddBasePoint(point);
     }
 }
Ejemplo n.º 3
0
		// The base class gathers mouse events and calls AnalyzeGesture()

		protected override bool AddFiltered(Util.WinForms.DragState state_, DragPoint dp)
		{
			DragState state = (DragState)state_;
			if (state.ClickedShape != null && state.ClickedShape.AllowsDrag)
				return false; // gesture recognition is off
			return base.AddFiltered(state, dp);
		}
 public FilteredChatBoxMessageEventProvider(IDecalEventsProxy decalEventsProxy, Util.ChatFlags chatFilter, Util.ChatChannels channelFilter)
 {
     this._decalEventsProxy = decalEventsProxy;
     this._chatFilter = chatFilter;
     this._channelFilter = channelFilter;
     this._decalEventsProxy.ChatBoxMessage += this.DecalEventsProxy_ChatBoxMessage;
 }
Ejemplo n.º 5
0
 //*********************************************************
 //*********************************************************
 // Constructor
 public hud(frmTerminal term)
 {
     InitializeComponent();
     m_term = term;
     m_util = new Util();
    
 }
Ejemplo n.º 6
0
    public string DeleteImageFile(Hashtable State, string url)
    {
        string AWSAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
        string AWSSecretKey = ConfigurationManager.AppSettings["AWSSecretKey"];
        string Bucket = ConfigurationManager.AppSettings["ImageBucket"];
        TransferUtility transferUtility = new TransferUtility(AWSAccessKey, AWSSecretKey);
        try
        {
            DeleteObjectRequest request = new DeleteObjectRequest();
            string file_name = url.Substring(url.LastIndexOf("/") + 1);
            string key = State["Username"].ToString() + "/" + file_name;
            request.WithBucketName(Bucket)
                .WithKey(key);
            using (DeleteObjectResponse response = transferUtility.S3Client.DeleteObject(request))
            {
                WebHeaderCollection headers = response.Headers;
             }
        }
        catch (AmazonS3Exception ex)
        {
            Util util = new Util();
            util.LogError(State, ex);
            return ex.Message + ": " + ex.StackTrace;
        }

        return "OK";
    }
Ejemplo n.º 7
0
    protected void Applications_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        ClearMessages();
        //get initial values
        if (e.Text.IndexOf("->") > 0)
        {
            HideForApplications();
            return;
        }

        ShowForApplications();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        string customer_id = State["ServerAdminCustomerID"].ToString();
        Util util = new Util();

        State["SelectedAdminApp"] = e.Text;
        string sql = "SELECT * FROM applications WHERE customer_id='" + customer_id + "' AND application_name='" + e.Text + "'";
        DB db = new DB();
        DataRow[] rows = db.ViziAppsExecuteSql(State, sql);
        string status = "";
        DataRow row = rows[0];
        string application_id = row["application_id"].ToString();

         State["application_id"] = application_id;

        status = row["status"].ToString();
        ApplicationStatus.Text = status;
        db.CloseViziAppsDatabase(State);
    }
Ejemplo n.º 8
0
 public void ZedGraphWrapper_MouseMove(Util.Variable.DataPoint point)
 {
     if (captureSwitch)
     {
         DisplayBasePointEvent(point);
     }
 }
    protected void AddTemplateApp_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "../../Default.aspx")) return;

        if (AppName.Text.Length == 0)
        {
            Message.Text = "Enter your own name for this app.";
            return;
        }
        string new_app_name = AppName.Text.Trim();
        if (!Check.ValidateObjectName(Message, new_app_name))
        {
            return;
        }

        if(util.DoesAppExistInAccount(State,new_app_name))
        {
            Message.Text = "The app name " + new_app_name + " already exists. Enter a unique app name.";
            return;
        }

         State["NameForTemplateApp"] = new_app_name;
        Ready.Text = "OK";
    }
Ejemplo n.º 10
0
 static void Main(string[] args)
 {
     if (args.Length == 0)
     {
         Console.WriteLine("Usage, MessageDecryptor.exe <pathtoencryptedfile.msg> (optional, any parameter to use the shell to open the file)");
         Console.WriteLine(" Output is written <pathtoencryptedfile.msg>.xml ");
         return;
     }
     Util u = new Util();
     try
     {
         File.WriteAllText(args[0] + ".xml", u.DE(File.ReadAllText(args[0])));
         Console.WriteLine("success");
         if (args.Length == 2)
         {
             try
             {
                 Process p = new Process();
                 p.StartInfo.UseShellExecute = true;
                 p.StartInfo.FileName = args[0] + ".xml";
                 p.Start();
                 p.Close();
                 p.Dispose();
             }
             catch { }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Ejemplo n.º 11
0
        private void SetIoc()
        {
            var resolverContainer = new SimpleContainer();

            var app = new XFormsAppiOS();
            app.Init(this);
            resolverContainer.Register<IXFormsApp>(app);

            var documents = app.AppDataDirectory;

            //resolverContainer.Register<IGeolocator, Geolocator>();
            //resolverContainer.Register<IEmailService, EmailService>();
            //resolverContainer.Register<IMediaPicker, MediaPicker>();
            //resolverContainer.Register<IDevice>( t => AppleDevice.CurrentDevice);
            Resolver.SetResolver(resolverContainer.GetResolver());

            DependencyService.Register<Geolocator> ();

            //resolverContainer.Register<IDevice>(t => AndroidDevice.CurrentDevice);
            //Resolver.SetResolver(resolverContainer.GetResolver());

            Console.WriteLine ("Here");
            Util util = new Util ();
            util.EnableLocationServices ();

            //manager.AuthorizationChanged += (sender, args) => {
               // Console.WriteLine ("Authorization changed to: {0}", args.Status);
            //};
            //if (UIDevice.CurrentDevice.CheckSystemVersion(8,0))
            //    manager.RequestWhenInUseAuthorization();
        }
Ejemplo n.º 12
0
    public void AppPagesChanged(string page_name)
    {
        try
        {
            ClearMessages();
            if (SavedCanvasHtml.Text.Length > 0)
            {
                if (!SavePage())
                    return;
            }
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
            State["SelectedAppPage"] = page_name;
            PageName.Text = State["SelectedAppPage"].ToString();

            AppPages.SelectedValue = page_name;
            ShowPage(page_name);
        }
        catch (Exception ex)
        {
            Util util = new Util();
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
            util.LogError(State, ex);
            Message.Text = "Internal Error: " + ex.Message + ": " + ex.StackTrace;
        }
    }
Ejemplo n.º 13
0
    public XmlDocument GetCustomerInfo()
    {
        XmlUtil x_util = new XmlUtil();
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        XmlNode status = null;
        XmlDocument Response = new XmlDocument();
        XmlNode root = Response.CreateElement("response");
        Response.AppendChild(root);
        try
        {
            DB db = new DB();
            String sql = "SELECT COUNT(*) FROM customers WHERE status!='inactive'";
            String count = db.ViziAppsExecuteScalar(State, sql);
            x_util.CreateNode(Response, root, "customer_count", count);
            db.CloseViziAppsDatabase(State);
            x_util.CreateNode(Response, root, "status", "success");
        }
        catch (System.Exception SE)
        {
            util.LogError(State, SE);

            if (status == null)
            {
                Response = new XmlDocument();
                XmlNode root2 = Response.CreateElement("response");
                Response.AppendChild(root2);
                status = x_util.CreateNode(Response, root2, "status");

            }
            status.InnerText = SE.Message;
            util.LogError(State, SE);
        }
        return Response;
    }
        // Util util = new Util(SecretConstants.BASE_URL);

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {

                Util util = new Util(SecretConstants.BASE_URL);

                if (Session["token"] == null)
                {
                    string token = util.GetAccessToken(SecretConstants.CLIENT_ID,
                       SecretConstants.CLIENT_SECRET).access_token;
                    if (token == string.Empty)
                    {
                        //LogExtensions.Log("Authentication error");
                    }
                    Session["token"] = token;
                }

                bool bucketExist = util.IsBucketExist(SecretConstants.DEFAULT_BUCKET_KEY, Session["token"].ToString());
                if (!bucketExist)
                {
                    util.CreateBucket(SecretConstants.DEFAULT_BUCKET_KEY, Session["token"].ToString());
                }

            }

        }
Ejemplo n.º 15
0
    //привязка компонентов к предметам
    public static Type GetAIObjects( Util.Map.Location map, int id )
    {
        Type component = null;
        switch (map) {
            case Util.Map.Location.Atlans:
                switch (id) {
                    case 24: component = typeof(MuMap.AI.AtlansDoor); break;
                }
            break;

            case Util.Map.Location.Devias:
                switch (id) {
                    case 21: case 89: component = typeof(MuMap.AI.SimpleDoor); break;
                    case 87: component = typeof(MuMap.AI.GateDoor); break;
                    case 82: case 83: case 99: case 100: component = typeof(MuMap.AI.Roof); break;
                }
            break;
            case Util.Map.Location.Lorencia:
                switch (id) {
                    case 126: case 127: component = typeof(MuMap.AI.Roof); break;
                }
            break;
        }

        return component;
    }
Ejemplo n.º 16
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         HelpClick.Attributes.Add("onclick", PopupHelper.GeneratePopupScript(
                    "../../Help/Design/AppTypeHelp.htm", 260, 530, false, false, false, false));
         Util util = new Util();
         Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
         if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;
         XmlUtil x_util = new XmlUtil();
         AppType.Items.Clear();
         AppType.Items.Add(new RadComboBoxItem("Select ->", "->"));
         switch (State["SelectedAppType"].ToString())
         {
             case Constants.NATIVE_APP_TYPE:
                 AppType.Items.Add(new RadComboBoxItem("Web App Type (no accecss to native device resources)", Constants.WEB_APP_TYPE));
                 AppType.Items.Add(new RadComboBoxItem("Hybrid App Type", Constants.HYBRID_APP_TYPE));
                 break;
             case Constants.WEB_APP_TYPE:
                 AppType.Items.Add(new RadComboBoxItem("Native App Type", Constants.NATIVE_APP_TYPE));
                 AppType.Items.Add(new RadComboBoxItem("Hybrid App Type", Constants.HYBRID_APP_TYPE));
                  break;
             case Constants.HYBRID_APP_TYPE:
                  AppType.Items.Add(new RadComboBoxItem("Web App Type (no accecss to native device resources)", Constants.WEB_APP_TYPE));
                  AppType.Items.Add(new RadComboBoxItem("Native App Type", Constants.NATIVE_APP_TYPE));
                 break;
         }
     }
 }
    protected void CopyApplicationButton_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "../Default.aspx")) return;

        if (Applications.Text.IndexOf("->") > 0)
        {
            Message.Text = "Select Application.";
            return;
        }
        if (ToAccounts.Text.IndexOf("->") > 0)
        {
            Message.Text = "Select Destination Account.";
            return;
        }
        if (ToAccounts.Text == FromAccounts.Text)
        {
            Message.Text = "Select a Different Destination Account.";
            return;
        }

        string app_name = Applications.SelectedItem.Text;

        //copy application
        util.CopyAppToAccount(State, app_name);
        Message.Text = "Application Copy is Successful.";
    }
Ejemplo n.º 18
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            try
            {
                util=new Util();
                CreateFolders();
                CreateFiles();

                if (AppearanceManager.Current != null)
                {
                    try
                    {
                        AppearanceManager.Current.AccentColor = Settings.Default.Color;
                        AppearanceManager.Current.FontSize = Settings.Default.FontSize;
                        AppearanceManager.Current.ThemeSource = Settings.Default.ThemeSource;
                        File.WriteAllText(@"C:\Users\sijo\Desktop\dlt\s.txt", "color " + Settings.Default.Color + "\nfont " + Settings.Default.FontSize + "\ntheme " + Settings.Default.ThemeSource);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception)
            {}
        }
Ejemplo n.º 19
0
        public static Util GetInstance()
        {
            if(_instance ==null)
                _instance = new Util();

            return _instance;
        }
Ejemplo n.º 20
0
 /// <summary>
 /// This adds a LinkedList of objects
 /// </summary>
 /// <param name="actorList">The list of objects</param>
 public void Add(Util.LinkedList actorList)
 {
     foreach(DXMAN.Physics.xVolume obj in m_xObjects)
     {
         Add(obj);
     }
 }
        public void ProcessRequest(HttpContext context)
        {
            string respJson = string.Empty;

            Util util = new Util(SecretConstants.BASE_URL);

            AccessToken token = util.GetAccessToken(SecretConstants.CLIENT_ID,
                SecretConstants.CLIENT_SECRET);


            if (context.Session["token"] == null)
            {
                string accessToken = token.access_token;
                if (accessToken == string.Empty)
                {
                    //LogExtensions.Log("Authentication error");
                }
                context.Session["token"] = accessToken;
            }

            respJson = Newtonsoft.Json.JsonConvert.SerializeObject(token);
          
            context.Response.ContentType = "application/json";
            context.Response.Write(respJson);
        }
    protected void Save_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "../../Default.aspx")) return;

        string name = UrlAccountIdentifier.Value.Trim();
        if (name.Length == 0)
        {
            Message.Text = "Enter Account Identifier Name";
            return;
        }
        if (!IsStringAlphaNumericPeriod(name) || name == ".")
        {
            Message.Text = "Domain Name should only use alphanumeric characters or '.'";
            return;
        }
        if (util.DoesUrlAccountIdentifierExist((Hashtable)HttpRuntime.Cache[Session.SessionID], name))
            Message.Text = "Account Identifier " + name + " is not Available.";
        else
        {
            UrlAccountIdentifier.Value = name;
            util.SaveUrlAccountIdentifier((Hashtable)HttpRuntime.Cache[Session.SessionID], name);
             State["UrlAccountIdentifier"] = name;
            Message.Text = "Account Identifier " + name + " has been saved. ";
        }
    }
Ejemplo n.º 23
0
    /***************************************** Common Functions *******************************/
    public void ManageDataApps_SelectedIndexChanged(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;

        ClearMessages();

         State["ManageDataType"] = null;
        string app_name = Request.Form.Get("ManageDataApps");
        if (!app_name.Contains("->"))
        {
             State["SelectedApp"] = app_name;
            ManageDataApps.SelectedValue = app_name;
            InitDataTrees(app_name);
            ViewStoryBoard.Style.Value = "";
            ManageDataType.Style.Value = "";
            ManageDataTypeLabel.Style.Value = "";
        }
        else
        {
            ManageDataType.Style.Value = "display:none";
            ManageDataTypeLabel.Style.Value = "display:none";
            ViewStoryBoard.Style.Value = "display:none";
            util.ResetAppStateVariables(State);
            ContentMultiPage.SelectedIndex = 0;
            ShouldRefreshStoryBoard.Text = "close";
            Init init = new Init();
            init.InitManageDataAppsList(State);
            DataMultiPage.SelectedIndex = 3;
        }
    }
Ejemplo n.º 24
0
    public void ResetDataResponseMap_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;

        ClearMessages();
        XmlDocument doc = util.GetStagingAppXml(State);
        XmlNode web_service_data_responses = doc.SelectSingleNode("//web_service_data_responses");
        if (web_service_data_responses != null)
        {
            web_service_data_responses.RemoveAll();
        }

        XmlNode phone_data_requests = doc.SelectSingleNode("//phone_data_requests");
        if (phone_data_requests == null)
            return;
        XmlNodeList event_fields = phone_data_requests.SelectNodes("phone_data_request/event_field");
        foreach (XmlNode event_field in event_fields)
        {
            XmlNode phone_data_request = event_field.ParentNode;
            XmlNodeList output_mappings = phone_data_request.SelectNodes("output_mapping");
            foreach (XmlNode output_mapping in output_mappings)
            {
                phone_data_request.RemoveChild(output_mapping);
            }
        }

        util.UpdateStagingAppXml(State);

        BuildWebServiceDataTrees(WebServiceEvents.SelectedItem.Text);
        ResponseMessage.Text = "Response Map Reset.";
        ResponseTreeEdits.Text = "";
    }
Ejemplo n.º 25
0
        public void Update(CustomList<BaseItem> itemList, Util.OperationType operationType)
        {
            String spName = String.Empty;

            switch (operationType)
            {
                case Util.OperationType.Insert:
                    spName = itemList.InsertSpName;
                    break;

                case Util.OperationType.Update:
                    spName = itemList.UpdateSpName;
                    break;

                case Util.OperationType.Delete:
                    spName = itemList.DeleteSpName;
                    break;
            }

            Object[] parameterValues = null;
            foreach (BaseItem item in itemList)
            {
                parameterValues = item.GetParameterValues();

                if (parameterValues.IsNotNull())
                {
                    DataAccessHelper.ExecuteNonQueryProcedure(transaction, spName, parameterValues);
                }
            }
        }
    protected void GetSpreadsheets_Click(object sender, EventArgs e)
    {
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        Util util = new Util();
        if (util.CheckSessionTimeout(State, Response, "../Default.aspx")) return;

        ClearMessages();
        if (! State["AccountType"].ToString().Contains("google_apps"))
        {
            if (Username.Text.Length == 0)
            {
                SaveGoogleDocsInfoMessage.Text = "Enter your Google Docs account username.";
                return;
            }
            if (Password.Text.Length == 0)
            {
                SaveGoogleDocsInfoMessage.Text = "Enter your Google Docs account password.";
                return;
            }
            else
                 State["GDocsPassword"] = Password.Text.Trim();
        }
        GDocs gDocs = new GDocs();
        String ret = gDocs.GetSpreadsheets(State, AccountSpreadsheets, Username.Text.Trim(),Password.Text.Trim());
        if (ret != "OK")
            SaveGoogleDocsInfoMessage.Text = "Either the username or password was not valid. "+ ret;
    }
        public void addGrafica(Util.Formula f, DataTable dt)
        {
            tablas[posActual] = dt;
            formulas[posActual] = f;

            aumentarPos();
        }
Ejemplo n.º 28
0
        //zaki - Insert record and get Scope_Identity()
        public object Insert(CustomList<BaseItem> itemList, Util.OperationType operationType)
        {
            String spName = String.Empty;

            switch (operationType)
            {
                case Util.OperationType.Insert:
                    spName = itemList.InsertSpName;
                    break;

                case Util.OperationType.Update:
                    spName = itemList.UpdateSpName;
                    break;

                case Util.OperationType.Delete:
                    spName = itemList.DeleteSpName;
                    break;
            }

            Object[] parameterValues = null;
            object retVal = null;

            parameterValues = itemList[0].GetParameterValues();

            if (parameterValues.IsNotNull())
            {
               retVal = DataAccessHelper.ExecuteScalar(transaction, spName, parameterValues);
            }

            return retVal;
        }
    protected void pickerType_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        Util util = new Util();
        if (util.CheckSessionTimeout(State, Response, "../Default.aspx")) return;

        pickerType.SelectedValue = e.Value;
        SectionMessage.Visible = true;
        section_names.Visible = true;
        switch (e.Value)
        {
            case "time":
            case "date":
                SectionMessage.Visible = false;
                section_names.Visible = false;
                SectionPages.SelectedIndex = 0;
                break;
            case "1_section":
                SectionMessage.Text = "Enter the Section Name";
                SectionPages.SelectedIndex = 1;
                break;
            case "2_sections":
                SectionMessage.Text = "Enter 2 Section Names separated by a comma";
                SectionPages.SelectedIndex = 2;
                break;
            case "3_sections":
                SectionMessage.Text = "Enter 3 Section Names separated by commas";
                SectionPages.SelectedIndex = 3;
                break;
            case "4_sections":
                SectionMessage.Text = "Enter 4 Section Names separated by commas";
                SectionPages.SelectedIndex = 4;
                break;
        }
    }
Ejemplo n.º 30
0
 //трава
 public static Grass[] GetDetailsList(Util.Map.Location map)
 {
     Grass[] textures = new Grass[0];
     switch (map) {
         case Util.Map.Location.Lorencia:	textures	= new Grass[]{
             new Grass(){ file = "TileGrass01", dry = Color.yellow, healthy = Color.green, minHeight = 100, maxHeight = 120 }
         }; break;
         case Util.Map.Location.Devias:	textures	= new Grass[]{
             new Grass(){ file = "TileGrass02", dry = Color.white, healthy = Color.white, minHeight = 50, maxHeight = 100 },
             new Grass(){ file = "TileGrass02", dry = Color.white, healthy = Color.white, minHeight = 50, maxHeight = 100 }
         }; break;
         case Util.Map.Location.Noria:		textures	= new Grass[]{
             new Grass(){ file = "TileGrass01", dry = Color.yellow, healthy = Color.green, minHeight = 150, maxHeight = 200 },
             null,
             new Grass(){ file = "TileGrass03", dry = Color.yellow, healthy = Color.yellow, minHeight = 200, maxHeight = 300 }
         }; break;
         case Util.Map.Location.DareDevil:	textures	= new Grass[]{
             new Grass(){ file = "TileGrass01", dry = Color.yellow, healthy = Color.yellow, minHeight = 150, maxHeight = 200 },
             new Grass(){ file = "TileGrass02", dry = Color.white, healthy = Color.white, minHeight = 150, maxHeight = 200 },
             new Grass(){ file = "TileGrass03", dry = Color.yellow, healthy = Color.yellow, minHeight = 200, maxHeight = 300 }
         }; break;
         case Util.Map.Location.Stadium:	textures	= new Grass[]{
             new Grass(){ file = "TileGrass01", dry = Color.yellow, healthy = Color.yellow, minHeight = 100, maxHeight = 150 }
         }; break;
         case Util.Map.Location.Tarcan:	textures	= new Grass[]{
             new Grass(){ file = "TileGrass01", dry = Color.gray, healthy = Color.gray, minHeight = 200, maxHeight = 300 },
             null,
             new Grass(){ file = "TileGrass03", dry = Color.yellow, healthy = Color.yellow, minHeight = 200, maxHeight = 300 }
         }; break;
     }
     return textures;
 }
 public void KillServer()
 {
   CacheHelper.StopJavaServer(1);
   Util.Log("Cacheserver 1 stopped.");
 }
    public void StepThreeRS()
    {
      bool ErrorOccurred = false;

      QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);

      var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

      int qryIdx = 0;

      foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries)
      {
        if (qrystr.Category == QueryCategory.Unsupported)
        {
          Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
          qryIdx++;
          continue;
        }

        if (m_isPdx == true)
        {
          if (qryIdx == 2 || qryIdx == 3 || qryIdx == 4)
          {
            Util.Log("Skipping query index {0} for Pdx because it is function type.", qryIdx);
            qryIdx++;
            continue;
          }
        }

        Util.Log("Evaluating query index {0}. Query string {1}", qryIdx, qrystr.Query);

        Query<object> query = qs.NewQuery<object>(qrystr.Query);

        ISelectResults<object> results = query.Execute();

        int expectedRowCount = qh.IsExpectedRowsConstantRS(qryIdx) ?
          QueryStatics.ResultSetRowCounts[qryIdx] : QueryStatics.ResultSetRowCounts[qryIdx] * qh.PortfolioNumSets;

        if (!qh.VerifyRS(results, expectedRowCount))
        {
          ErrorOccurred = true;
          Util.Log("Query verify failed for query index {0}.", qryIdx);
          qryIdx++;
          continue;
        }

        ResultSet<object> rs = results as ResultSet<object>;

        foreach (object item in rs)
        {
          if (!m_isPdx)
          {
            Portfolio port = item as Portfolio;
            if (port == null)
            {
              Position pos = item as Position;
              if (pos == null)
              {
                string cs = item.ToString();
                if (cs == null)
                {
                  Util.Log("Query got other/unknown object.");
                }
                else
                {
                  Util.Log("Query got string : {0}.", cs);
                }
              }
              else
              {
                Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
              }
            }
            else
            {
              Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
            }
          }
          else
          {
            PortfolioPdx port = item as PortfolioPdx;
            if (port == null)
            {
              PositionPdx pos = item as PositionPdx;
              if (pos == null)
              {
                string cs = item.ToString();
                if (cs == null)
                {
                  Util.Log("Query got other/unknown object.");
                }
                else
                {
                  Util.Log("Query got string : {0}.", cs);
                }
              }
              else
              {
                Util.Log("Query got Position object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding);
              }
            }
            else
            {
              Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
            }
          }
        }

        qryIdx++;
      }

      Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
    }
        public FamilySymbol GetColumnFamilySymbol(Document doc, Column col, string familyName, BuiltInCategory category)
        {
            string b = category == BuiltInCategory.OST_StructuralColumns ? "b" : "Width";
            string h = category == BuiltInCategory.OST_StructuralColumns ? "h" : "Depth";

            FamilySymbol fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .Where(f => f.FamilyName == familyName)
                                                        .FirstOrDefault(f =>
                                                        {
                                                            if (f.LookupParameter(h).AsDouble() == Util.MmToFoot(col.Depth) &&
                                                                    f.LookupParameter(b).AsDouble() == Util.MmToFoot(col.Width))
                                                            {
                                                                return true;
                                                            }
                                                            return false;
                                                        });

            if (fs != null) return fs;

            Family family = default;
            try
            {
                fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .First(f => f.FamilyName == familyName);
            }
            catch (Exception)
            {
                string directory = $"C:/ProgramData/Autodesk/RVT {revitVersion}/Libraries/US Imperial/Structural Columns/Concrete/";
                family = OpenFamily(doc, directory, familyName);
                fs = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
            }

            ElementType fs1 = fs.Duplicate(String.Format("Column {0:0}x{1:0}", col.Width / 10, col.Depth / 10));
            fs1.LookupParameter(b).Set(Util.MmToFoot(col.Width));
            fs1.LookupParameter(h).Set(Util.MmToFoot(col.Depth));
            return fs1 as FamilySymbol;
        }
 public FamilyInstance CreateSteelBeamInstance(Document doc, BeamSt beam, FamilySymbol fs)
 {
     StructuralType stBeam = StructuralType.Beam;
     XYZ p1 = new XYZ(Util.MmToFoot(beam.Location.X), Util.MmToFoot(beam.Location.Y), Util.MmToFoot(beam.Location.Z));
     XYZ p2 = p1 + beam.Length * new XYZ(Util.MmToFoot(beam.Axis.X), Util.MmToFoot(beam.Axis.Y), Util.MmToFoot(beam.Axis.Z));
     Line l1 = Line.CreateBound(p1, p2);
     FamilyInstance fi = doc.Create.NewFamilyInstance(l1, fs, null, stBeam);
     fi.LookupParameter("Reference Level").Set(GetLevel(doc, beam.Location.Z).Id);
     return fi;
 }
        public List<Grid>[] CreateGrids(Document doc, List<double> xLocations, List<double> yLocations)
        {

            List<Grid> xGrids = xLocations.Select(yCoord => Line.CreateBound(new XYZ(yLocations.Min() - Util.MmToFoot(2000), yCoord, 0),
                                                                         new XYZ(yLocations.Max() + Util.MmToFoot(2000), yCoord, 0)))
                                            .Select(line => Grid.Create(doc, line)).ToList();

            xGrids.ForEach(grid => grid.Name = Encoding.ASCII.GetString(new byte[1] { xGridName++ }));


            List<Grid> yGrids = yLocations.Select(xCoord => Line.CreateBound(new XYZ(xCoord, xLocations.Min() - Util.MmToFoot(2000), 0),
                                                                         new XYZ(xCoord, xLocations.Max() + Util.MmToFoot(2000), 0))).ToList()
                                            .Select(line => Grid.Create(doc, line)).ToList();

            yGrids.ForEach(grid => grid.Name = (yGridName++).ToString());

            return new List<Grid>[2] { xGrids, yGrids };

        }
        public FamilyInstance CreateBraceInstance(Document doc, Brace Brace, FamilySymbol colType, bool isStructural, List<double> storeys)
        {
            XYZ location = new XYZ(Util.MmToFoot(Brace.Location.X), Util.MmToFoot(Brace.Location.Y), Util.MmToFoot(Brace.Location.Z));
            XYZ endLocation = location + Util.MmToFoot(Brace.Length) * new XYZ(Brace.Axis.X, Brace.Axis.Y, Brace.Axis.Z);

            Level colBottomLevel = GetLevel(doc, MapToStorey(Brace.BottomLevel, storeys));
            double toplevel = Util.FootToMm(endLocation.Z);
            Level colTopLevel = GetLevel(doc, MapToStorey(toplevel, storeys));

            double colRotation = Brace.RefDirection.X >= 0.0 ?
                90 + Vector3D.AngleBetween(new Vector3D(Brace.RefDirection.X, Brace.RefDirection.Y, Brace.RefDirection.Z), new Vector3D(0, -1, 0)) :
                90 + Vector3D.AngleBetween(new Vector3D(Brace.RefDirection.X, Brace.RefDirection.Y, Brace.RefDirection.Z), new Vector3D(0, -1, 0));

            colRotation *= Math.PI / 180.0;

            return CreateBraceInstance(doc, location, endLocation, colBottomLevel, colTopLevel, colType, colRotation, isStructural);
        }
Ejemplo n.º 37
0
 private void btnChangeColor_Click(object sender, EventArgs e)
 {
     cf.BackColor = Util.GetRandomColor();
 }
        public Level GetLevel(Document doc, double elevation)
        {
            Level rLevel;

            try
            {
                rLevel = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels)
                                                        .WhereElementIsNotElementType()
                                                        .Cast<Level>()
                                                        .First(lvl => lvl.Elevation == Util.MmToFoot(elevation));
            }
            catch (Exception)
            {
                rLevel = Level.Create(doc, Util.MmToFoot(elevation));
                rLevel.LookupParameter("Name").Set(String.Format("Level {0}", lvlNumber++));
            }

            return rLevel;
        }
        public FamilySymbol GetBeamFamilySymbol(Document doc, Beam beam, string familyName, BuiltInCategory category)
        {
            FamilySymbol fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .Where(f => f.FamilyName == familyName)
                                                        .FirstOrDefault(f =>
                                                        {
                                                            if (Math.Abs(f.LookupParameter("h").AsDouble() - Util.MmToFoot(beam.H)) < Util.MmToFoot(0.001) &&
                                                                Math.Abs(f.LookupParameter("b").AsDouble() - Util.MmToFoot(beam.B)) < Util.MmToFoot(0.001))

                                                                return true;
                                                            return false;
                                                        });

            if (fs != null) return fs;
            Family family = default;

            try
            {
                fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .First(f => f.FamilyName == familyName);

            }
            catch (Exception)
            {
                string directory = $"C:/ProgramData/Autodesk/RVT {revitVersion}/Libraries/US Imperial/Structural Framing/Concrete/";
                family = OpenFamily(doc, directory, familyName);
                fs = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;

            }
            ElementType fs1 = fs.Duplicate(String.Format("Beam {0:0}x{1:0}", beam.B / 10, beam.H / 10));
            fs1.LookupParameter("h").Set(Util.MmToFoot(beam.H));
            fs1.LookupParameter("b").Set(Util.MmToFoot(beam.B));
            return fs1 as FamilySymbol;
        }
Ejemplo n.º 40
0
 private void btnChangeState_Click(object sender, EventArgs e)
 {
     cf.WindowState = Util.GetRandomState(cf.WindowState);
 }
Ejemplo n.º 41
0
        public void Remove(EditorActorPreview preview)
        {
            previews.Remove(preview);
            screenMap.Remove(preview);

            // Fallback to the actor's CenterPosition for the ActorMap if it has no Footprint
            var footprint = preview.Footprint.Select(kv => kv.Key).ToArray();

            if (!footprint.Any())
            {
                footprint = new[] { worldRenderer.World.Map.CellContaining(preview.CenterPosition) }
            }
            ;

            foreach (var cell in footprint)
            {
                if (!cellMap.TryGetValue(cell, out var list))
                {
                    continue;
                }

                list.Remove(preview);

                if (!list.Any())
                {
                    cellMap.Remove(cell);
                }
            }

            preview.RemovedFromEditor();
            UpdateNeighbours(preview.Footprint);

            if (preview.Info.Name == "mpspawn")
            {
                SyncMultiplayerCount();
            }
        }

        void SyncMultiplayerCount()
        {
            var newCount = previews.Count(p => p.Info.Name == "mpspawn");
            var mp       = Players.Players.Where(p => p.Key.StartsWith("Multi")).ToList();

            foreach (var kv in mp)
            {
                var name  = kv.Key;
                var index = int.Parse(name.Substring(5));

                if (index >= newCount)
                {
                    Players.Players.Remove(name);
                    OnPlayerRemoved();
                }
            }

            for (var index = 0; index < newCount; index++)
            {
                if (Players.Players.ContainsKey("Multi{0}".F(index)))
                {
                    continue;
                }

                var pr = new PlayerReference
                {
                    Name     = "Multi{0}".F(index),
                    Faction  = "Random",
                    Playable = true,
                    Enemies  = new[] { "Creeps" }
                };

                Players.Players.Add(pr.Name, pr);
                worldRenderer.UpdatePalettesForPlayer(pr.Name, pr.Color, true);
            }

            var creeps = Players.Players.Keys.FirstOrDefault(p => p == "Creeps");

            if (!string.IsNullOrEmpty(creeps))
            {
                Players.Players[creeps].Enemies = Players.Players.Keys.Where(p => !Players.Players[p].NonCombatant).ToArray();
            }
        }

        void UpdateNeighbours(IReadOnlyDictionary <CPos, SubCell> footprint)
        {
            // Include actors inside the footprint too
            var cells = Util.ExpandFootprint(footprint.Keys, true);

            foreach (var p in cells.SelectMany(c => PreviewsAt(c)))
            {
                p.ReplaceInit(new RuntimeNeighbourInit(NeighbouringPreviews(p.Footprint)));
            }
        }

        void AddPreviewLocation(EditorActorPreview preview, CPos location)
        {
            if (!cellMap.TryGetValue(location, out var list))
            {
                list = new List <EditorActorPreview>();
                cellMap.Add(location, list);
            }

            list.Add(preview);
        }

        Dictionary <CPos, string[]> NeighbouringPreviews(IReadOnlyDictionary <CPos, SubCell> footprint)
        {
            var cells = Util.ExpandFootprint(footprint.Keys, true).Except(footprint.Keys);

            return(cells.ToDictionary(c => c, c => PreviewsAt(c).Select(p => p.Info.Name).ToArray()));
        }
Ejemplo n.º 42
0
 protected void DoAction(object sender, EventArgs e)
 {
     Util.CloseRadWindow(this, ((Button)sender).ID, false);
 }
    public void getTutorialPrepareData(ToC_PREPARE_TUTORIAL p)
    {
        isStart = false;

        isTutorialSkipCheckMode = true;
        uiTutorial.openTutorialDialog(186, 457, Util.getUIText("CONFIRM_TUTORIAL", GameManager.info.tutorialInfoData[readyTutorialId].title), false);
        uiTutorial.goDialogYesNoButtonContainer.SetActive(true);

        int i = 0;

        if (p.ruby > 0)
        {
            uiTutorial.spPrepareRewardIcon[i].spriteName = WSDefine.ICON_RUBY;
            uiTutorial.spPrepareRewardIcon[i].MakePixelPerfect();
            uiTutorial.lbPrepareRewardLabel[i].text = Util.GetCommaScore(p.ruby);

            ++i;
        }

        if (p.gold > 0)
        {
            uiTutorial.spPrepareRewardIcon[i].spriteName = WSDefine.ICON_GOLD;
            uiTutorial.spPrepareRewardIcon[i].MakePixelPerfect();
            uiTutorial.lbPrepareRewardLabel[i].text = Util.GetCommaScore(p.gold);

            ++i;
        }

        if (p.energy > 0)
        {
            uiTutorial.spPrepareRewardIcon[i].spriteName = WSDefine.ICON_ENERGY;
            uiTutorial.spPrepareRewardIcon[i].MakePixelPerfect();
            uiTutorial.lbPrepareRewardLabel[i].text = Util.GetCommaScore(p.energy);

            ++i;
        }

        if (p.exp > 0 && i < 3)
        {
            uiTutorial.spPrepareRewardIcon[i].spriteName = WSDefine.ICON_EXP;
            uiTutorial.spPrepareRewardIcon[i].MakePixelPerfect();
            uiTutorial.lbPrepareRewardLabel[i].text = Util.GetCommaScore(p.exp);

            ++i;
        }

        switch (i)
        {
        case 1:
            uiTutorial.spPrepareRewardIcon[0].transform.parent.gameObject.SetActive(true);
            uiTutorial.spPrepareRewardIcon[1].transform.parent.gameObject.SetActive(false);
            uiTutorial.spPrepareRewardIcon[2].transform.parent.gameObject.SetActive(false);

            uiTutorial.spPrepareRewardIcon[0].transform.parent.transform.localPosition = new Vector3(-76, 84, 18);
            break;

        case 2:
            uiTutorial.spPrepareRewardIcon[0].transform.parent.gameObject.SetActive(true);
            uiTutorial.spPrepareRewardIcon[1].transform.parent.gameObject.SetActive(true);
            uiTutorial.spPrepareRewardIcon[2].transform.parent.gameObject.SetActive(false);

            uiTutorial.spPrepareRewardIcon[0].transform.parent.transform.localPosition = new Vector3(-190, 84, 18);
            uiTutorial.spPrepareRewardIcon[1].transform.parent.transform.localPosition = new Vector3(40, 84, 18);

            break;

        case 3:
            uiTutorial.spPrepareRewardIcon[0].transform.parent.gameObject.SetActive(true);
            uiTutorial.spPrepareRewardIcon[1].transform.parent.gameObject.SetActive(true);
            uiTutorial.spPrepareRewardIcon[2].transform.parent.gameObject.SetActive(true);

            uiTutorial.spPrepareRewardIcon[0].transform.parent.transform.localPosition = new Vector3(-252, 84, 18);
            uiTutorial.spPrepareRewardIcon[1].transform.parent.transform.localPosition = new Vector3(-76, 84, 18);
            uiTutorial.spPrepareRewardIcon[2].transform.parent.transform.localPosition = new Vector3(97, 84, 18);

            break;
        }



        switch (readyTutorialId)
        {
        case "T15":
            uiTutorial.lbPrepareRewardSpecial.text                    = Util.getUIText("TT15_SP");
            uiTutorial.spPrepareRewardSpecialCover.enabled            = true;
            uiTutorial.lbPrepareRewardSpecial.transform.localPosition = new Vector3(-192, -636, -19);
            break;

        default:
            uiTutorial.lbPrepareRewardSpecial.transform.localPosition = new Vector3(-192, -654, -19);
            uiTutorial.spPrepareRewardSpecialCover.enabled            = false;
            uiTutorial.lbPrepareRewardSpecial.text = "";
            break;
        }
    }
Ejemplo n.º 44
0
            public void DrawProperties()
            {
                if ((m_axis == Axis.X && !GridSettings.instance.showXAxisOptions) ||
                    (m_axis == Axis.Y && !GridSettings.instance.showYAxisOptions) ||
                    (m_axis == Axis.Z && !GridSettings.instance.showZAxisOptions))
                {
                    return;
                }

                AxisProperties axisProperties = m_gridData.GetAxisProperties(m_axis);

                EditorGUI.BeginChangeCheck();

                Color originalBGColor = GUI.backgroundColor;

                GUI.backgroundColor = GetAxisColor(m_axis);

                GUIStyle style = new GUIStyle(GUI.skin.box);

                style.normal.background = EditorTextures.GetByName(EditorTextures.BORDER_TEX_NAME);
                style.border            = new RectOffset(5, 5, 5, 5);

                if (GridSettings.instance.gridWindowLayout == LayoutDirection.Vertical)
                {
                    EditorGUILayout.BeginVertical(style);
                }
                else
                {
                    EditorGUILayout.BeginHorizontal(style);
                }
                {
                    GUI.backgroundColor = originalBGColor;

                    m_isFoldoutOpen = EditorGUILayout.Foldout(m_isFoldoutOpen, m_axis + " Axis");

                    if (m_isFoldoutOpen)
                    {
                        // VISIBLE
                        axisProperties.isVisibleInEditor =
                            EditorGUIExtensions.IconToggle(EditorTextures.GetTexturePath(EditorTextures.HIDDEN_ICON),
                                                           EditorTextures.GetTexturePath(EditorTextures.VISIBLE_ICON),
                                                           axisProperties.isVisibleInEditor,
                                                           "Hide the " + m_axis + " grid plane",
                                                           "Show the " + m_axis + " grid plane");

                        // SNAP
                        axisProperties.isSnapEnabled =
                            EditorGUIExtensions.IconToggle(EditorTextures.GetTexturePath(EditorTextures.POSITION_SNAP_DISABLED_ICON),
                                                           EditorTextures.GetTexturePath(EditorTextures.POSITION_SNAP_ENABLED_ICON),
                                                           axisProperties.isSnapEnabled,
                                                           "Disable snapping along the " + m_axis + " axis",
                                                           "Enable snapping along the " + m_axis + " axis");

                        string unitAbbrev = UnitUtil.Abbreviation(GridSettings.instance.measurementUnit);

                        EditorGUILayout.BeginVertical();
                        {
                            // CELL SIZE
                            EditorGUIExtensions.DrawIconPrefixedField(EditorTextures.GetTexturePath(EditorTextures.CELL_SIZE_ICON),
                                                                      "Size of cells along the " + m_axis + " axis",
                                                                      delegate
                            {
                                axisProperties.cellSize = (float)EditorUnitUtil.DrawConvertedSizeField(axisProperties.cellSize,
                                                                                                       Unit.Meter, GridSettings.instance.measurementUnit, GridWindow.MIN_FIELD_WIDTH);
                                axisProperties.cellSize = Mathf.Max(axisProperties.cellSize, MIN_SIZE);

                                EditorGUILayout.LabelField(unitAbbrev, GUILayout.Width(GridWindow.UNIT_LABEL_WIDTH));
                            });

                            // GRID OFFSET
                            EditorGUIExtensions.DrawIconPrefixedField(EditorTextures.GetTexturePath(EditorTextures.GRID_OFFSET_ICON),
                                                                      "Offset of the entire grid along the " + m_axis + " axis",
                                                                      delegate
                            {
                                axisProperties.offset = (float)EditorUnitUtil.DrawConvertedSizeField(axisProperties.offset, Unit.Meter,
                                                                                                     GridSettings.instance.measurementUnit, GridWindow.MIN_FIELD_WIDTH);

                                EditorGUILayout.LabelField(unitAbbrev, GUILayout.Width(GridWindow.UNIT_LABEL_WIDTH));
                            });
                        }
                        EditorGUILayout.EndVertical();

                        // ROTATION
                        EditorGUIExtensions.DrawIconPrefixedField(EditorTextures.GetTexturePath(EditorTextures.ROTATION_SNAP_ANGLE_ICON),
                                                                  "Rotation of the grid around the " + m_axis + " axis",
                                                                  delegate
                        {
                            axisProperties.rotation = EditorGUILayout.FloatField(axisProperties.rotation,
                                                                                 GUILayout.MinWidth(GridWindow.MIN_FIELD_WIDTH));
                            axisProperties.rotation = Util.Wrap(axisProperties.rotation, MIN_AXIS_ROTATION, MAX_AXIS_ROTATION);

                            // degree symbol
                            EditorGUILayout.LabelField(('\u00B0').ToString(), GUILayout.Width(GridWindow.UNIT_LABEL_WIDTH));
                        });
                    }

                    GUI.backgroundColor = GetAxisColor(m_axis);
                }
                if (GridSettings.instance.gridWindowLayout == LayoutDirection.Vertical)
                {
                    EditorGUILayout.EndVertical();
                }
                else
                {
                    EditorGUILayout.EndHorizontal();
                }

                GUI.backgroundColor = originalBGColor;

                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(m_gridData);
                    SavePrefs();
                }
            }
Ejemplo n.º 45
0
        protected override void Seed(GPSContext context)
        {
            context.Elements.AddOrUpdate(x => x.Name,
                                         new Node()
            {
                Name = "Glavni kolodvor", IsNode = true, X = 300, Y = 110
            },
                                         new Node()
            {
                Name = "Trg bana J.Jelacica", IsNode = true, X = 300, Y = 60
            },
                                         new Node()
            {
                Name = "Kaptol", IsNode = true, X = 300, Y = 40
            },
                                         new Node()
            {
                Name = "PMF", IsNode = true, X = 350, Y = 25
            },
                                         new Node()
            {
                Name = "Britanski trg", IsNode = true, X = 150, Y = 60
            },
                                         new Node()
            {
                Name = "Lisinski", IsNode = true, X = 310, Y = 130
            },
                                         new Node()
            {
                Name = "Zagrepcanka", IsNode = true, X = 180, Y = 130
            },
                                         new Node()
            {
                Name = "Studentski dom S.Radic", IsNode = true, X = 180, Y = 290
            },
                                         new Node()
            {
                Name = "Avenue Mall", IsNode = true, X = 310, Y = 290
            }
                                         );

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Ulica Zrinjevac",
                IsNode          = false,
                StartId         = GetNodeId("Trg bana J.Jelacica", context),
                EndId           = GetNodeId("Glavni kolodvor", context),
                SingleDirection = false,
                Distance        = Util.Distance(300, 110, 300, 60)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Kaptol ulica",
                IsNode          = false,
                StartId         = GetNodeId("Trg bana J.Jelacica", context),
                EndId           = GetNodeId("Kaptol", context),
                SingleDirection = true,
                Distance        = Util.Distance(300, 60, 300, 40)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Ulica N.Grskovica",
                IsNode          = false,
                StartId         = GetNodeId("Kaptol", context),
                EndId           = GetNodeId("PMF", context),
                SingleDirection = false,
                Distance        = Util.Distance(300, 40, 350, 25)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Ilica",
                IsNode          = false,
                StartId         = GetNodeId("Trg bana J.Jelacica", context),
                EndId           = GetNodeId("Britanski trg", context),
                SingleDirection = true,
                Distance        = Util.Distance(300, 60, 150, 60)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Paromlinska cesta",
                IsNode          = false,
                StartId         = GetNodeId("Glavni kolodvor", context),
                EndId           = GetNodeId("Lisinski", context),
                SingleDirection = false,
                Distance        = Util.Distance(300, 110, 310, 130)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Ulica grada Vukovara",
                IsNode          = false,
                StartId         = GetNodeId("Lisinski", context),
                EndId           = GetNodeId("Zagrepcanka", context),
                SingleDirection = false,
                Distance        = Util.Distance(310, 130, 180, 130)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Savska cesta",
                IsNode          = false,
                StartId         = GetNodeId("Zagrepcanka", context),
                EndId           = GetNodeId("Studentski dom S.Radic", context),
                SingleDirection = false,
                Distance        = Util.Distance(180, 130, 180, 290)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Avenija Dubrovnik",
                IsNode          = false,
                StartId         = GetNodeId("Studentski dom S.Radic", context),
                EndId           = GetNodeId("Avenue Mall", context),
                SingleDirection = false,
                Distance        = Util.Distance(180, 290, 310, 290)
            });

            context.SaveChanges();

            context.Elements.AddOrUpdate(x => x.Name,
                                         new Edge()
            {
                Name            = "Avenija V.Holjevca",
                IsNode          = false,
                StartId         = GetNodeId("Lisinski", context),
                EndId           = GetNodeId("Avenue Mall", context),
                SingleDirection = false,
                Distance        = Util.Distance(310, 130, 310, 290)
            }
                                         );

            context.SaveChanges();

            context.Characteristics.AddOrUpdate(x => x.Id,
                                                new Characteristic()
            {
                Id                 = 1,
                ElementId          = GetNodeId("Trg bana J.Jelacica", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Trgovina
            },
                                                new Characteristic()
            {
                Id                 = 2,
                ElementId          = GetNodeId("Trg bana J.Jelacica", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Restoran
            },
                                                new Characteristic()
            {
                Id                 = 3,
                ElementId          = GetNodeId("Trg bana J.Jelacica", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Ljekarna
            },
                                                new Characteristic()
            {
                Id                 = 4,
                ElementId          = GetNodeId("Britanski trg", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Trgovina
            },
                                                new Characteristic()
            {
                Id                 = 5,
                ElementId          = GetNodeId("Glavni kolodvor", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Trgovina
            },
                                                new Characteristic()
            {
                Id                 = 6,
                ElementId          = GetNodeId("Glavni kolodvor", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Pošta
            },
                                                new Characteristic()
            {
                Id                 = 7,
                ElementId          = GetNodeId("Glavni kolodvor", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Benzinska
            },
                                                new Characteristic()
            {
                Id                 = 8,
                ElementId          = GetNodeId("Avenue Mall", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Trgovina
            },
                                                new Characteristic()
            {
                Id                 = 9,
                ElementId          = GetNodeId("Avenue Mall", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Garaža
            },
                                                new Characteristic()
            {
                Id                 = 10,
                ElementId          = GetNodeId("Avenue Mall", context),
                CharacteristicType = Characteristic.CharacteristicTypes.Restoran
            }



                                                );
        }
Ejemplo n.º 46
0
        /*
         * /// <summary>
         * /// 음표 하나를 재생합니다.
         * /// 이미 재생 중인 다른 음표와 동시에 재생할 수 있으며
         * /// 음표의 길이만큼 연주하고 음이 사라집니다.
         * /// </summary>
         * /// <param name="outDevice">출력 디바이스</param>
         * /// <param name="note">재생할 음표</param>
         * /// <param name="velocity">연주 세기 (0 ~ 127)</param>
         * // (만약 Unity에서 작업할 경우, 타입을 void 대신 IEnumerator로 바꿔서 Coroutine으로 사용하세요.)
         * public static void PlayANote(OutputDevice outDevice, Note note, int velocity = 127)
         * {
         *  // 이미 재생 중인 악보이면 중복하여 재생하지 않습니다.
         *  if (velocity < 0 || velocity >= 128) return;
         *  //Console.WriteLine("Playing...");
         *
         *  // 악보에 있는 모든 음표를 재생합니다.
         *  KeyValuePair<float, int> p = note.ToMidi()[0];
         *
         *  if (p.Value > 0)
         *  {
         *      // 음표를 재생합니다.
         *      // (Midi message pair를 번역하여 Midi message를 생성합니다.)
         *      try
         *      {
         *          outDevice.Send(new ChannelMessage(ChannelCommand.NoteOn, p.Value >> 16, p.Value & 65535, velocity));
         *      }
         *      catch (ObjectDisposedException) { }
         *      catch (OutputDeviceException) { }
         *  }
         *
         *  void noteOffBufferAdd(object[] args)
         *  {
         *      List<Note> noteOffBuffer_ = args[0] as List<Note>;
         *      Note note_ = args[1] as Note;
         *      noteOffBuffer_.Add(note_);
         *  }
         *
         *  Util.TaskQueue.Add("noteOffBuffer", noteOffBufferAdd, noteOffBuffer, note);
         *  //Console.WriteLine("End of note.");
         * }
         */

        /// <summary>
        /// 음표 하나를 재생합니다.
        /// 이미 재생 중인 다른 음표와 동시에 재생할 수 있으며
        /// 음표의 길이만큼 연주하고 음이 사라집니다.
        /// </summary>
        /// <param name="syn">신디사이저</param>
        /// <param name="note">재생할 음표</param>
        /// <param name="velocityChange">연주 세기를 변화시키기 위해 음 세기에 곱해질 값</param>
        public static void PlayANote(Synth syn, Note note, float velocityChange = 1f)
        {
            // 이미 재생 중인 악보이면 중복하여 재생하지 않습니다.
            if (velocityChange < 0)
            {
                return;
            }
            //Console.WriteLine("Playing...");

            void noteOffBufferCheckAndPlay(object[] args)
            {
                Dictionary <int, List <Note> > noteOffBuffer_ = args[0] as Dictionary <int, List <Note> >;
                Note  note_           = args[1] as Note;
                float velocityChange_ = (float)args[2];
                int   staff           = note_.Staff;
                int   pitch           = note_.Pitch;

                if (noteOffBuffer_.ContainsKey(staff))
                {
                    int i = noteOffBuffer_[staff].FindIndex((n) => (pitch == n.Pitch));
                    if (i != -1)
                    {
                        // 해당 채널에서 같은 음 높이의 음이 이미 재생 중인 경우
                        try
                        {
                            // 재생 중이었던 음표의 재생을 멈춥니다.
                            syn.NoteOff(staff, pitch);
                        }
                        catch (ObjectDisposedException) { }
                        catch (FluidSynthInteropException) { }
                        noteOffBuffer_[staff].RemoveAt(i);
                    }
                }

                KeyValuePair <float, int> p = note.ToMidi()[0];

                if (p.Value > 0)
                {
                    int velocity = Util.RoundAndClamp(note.Velocity * velocityChange_, 0, 127);
                    if (velocity == 0)
                    {
                        return;
                    }

                    // 음표를 재생합니다.
                    // (Midi message pair를 번역하여 Midi message를 생성합니다.)
                    try
                    {
                        syn.NoteOn(p.Value >> 16, p.Value & 65535, velocity);
                        if (!noteOffBuffer_.ContainsKey(staff))
                        {
                            noteOffBuffer_.Add(staff, new List <Note>());
                        }
                        noteOffBuffer_[staff].Add(note_);
                    }
                    catch (ObjectDisposedException) { }
                    catch (FluidSynthInteropException) { }
                }
            }

            Util.TaskQueue.Add("noteOffBuffer", noteOffBufferCheckAndPlay, noteOffBuffer, note, velocityChange);

            //Console.WriteLine("End of note.");
        }
 public EDI315MsgParsing()
 {
     util    = new Util();
     context = new DBContext();
 }
Ejemplo n.º 48
0
		public UIStatus(Transform parent, string objName)
		{
			Util.FindParentToChild(ref _tra, parent, objName);
			Util.FindParentToChild(ref _uiVal, _tra, "Val");
			Util.FindParentToChild(ref _uiLabel, _tra, "Label");
		}
Ejemplo n.º 49
0
        /// <summary>
        /// Performs startup specific to the region server, including initialization of the scene
        /// such as loading configuration from disk.
        /// </summary>
        protected override void StartupSpecific()
        {
            IConfig startupConfig = Config.Configs["Startup"];

            if (startupConfig != null)
            {
                // refuse to run MegaRegions
                if (startupConfig.GetBoolean("CombineContiguousRegions", false))
                {
                    m_log.Fatal("CombineContiguousRegions (MegaRegions) option is no longer suported. Use a older version to save region contents as OAR, then import into a fresh install of this new version");
                    throw new Exception("CombineContiguousRegions not suported");
                }

                string pidFile = startupConfig.GetString("PIDFile", String.Empty);
                if (pidFile != String.Empty)
                {
                    CreatePIDFile(pidFile);
                }

                userStatsURI = startupConfig.GetString("Stats_URI", String.Empty);

                m_securePermissionsLoading = startupConfig.GetBoolean("SecurePermissionsLoading", true);

                string permissionModules = Util.GetConfigVarFromSections <string>(Config, "permissionmodules",
                                                                                  new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule");

                m_permsModules = new List <string>(permissionModules.Split(',').Select(m => m.Trim()));

                managedStatsURI      = startupConfig.GetString("ManagedStatsRemoteFetchURI", String.Empty);
                managedStatsPassword = startupConfig.GetString("ManagedStatsRemoteFetchPassword", String.Empty);
            }

            // Load the simulation data service
            IConfig simDataConfig = Config.Configs["SimulationDataStore"];

            if (simDataConfig == null)
            {
                throw new Exception("Configuration file is missing the [SimulationDataStore] section.  Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");
            }

            string module = simDataConfig.GetString("LocalServiceModule", String.Empty);

            if (String.IsNullOrEmpty(module))
            {
                throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section.");
            }

            m_simulationDataService = ServerUtils.LoadPlugin <ISimulationDataService>(module, new object[] { Config });
            if (m_simulationDataService == null)
            {
                throw new Exception(
                          string.Format(
                              "Could not load an ISimulationDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [SimulationDataStore] config section.",
                              module));
            }

            // Load the estate data service
            module = Util.GetConfigVarFromSections <string>(Config, "LocalServiceModule", new string[] { "EstateDataStore", "EstateService" }, String.Empty);
            if (String.IsNullOrEmpty(module))
            {
                throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] or [EstateService] section");
            }

            if (LoadEstateDataService)
            {
                m_estateDataService = ServerUtils.LoadPlugin <IEstateDataService>(module, new object[] { Config });
                if (m_estateDataService == null)
                {
                    throw new Exception(
                              string.Format(
                                  "Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.",
                                  module));
                }
            }

            base.StartupSpecific();

            if (EnableInitialPluginLoad)
            {
                LoadPlugins();
            }

            // We still want to post initalize any plugins even if loading has been disabled since a test may have
            // inserted them manually.
            foreach (IApplicationPlugin plugin in m_plugins)
            {
                plugin.PostInitialise();
            }

            if (m_console != null)
            {
                AddPluginCommands(m_console);
            }
        }
Ejemplo n.º 50
0
    /// <summary>
    /// 初始JS
    /// </summary>
    void SchedulerInitJS()
    {
        string strResourceIDList = ucResourceIDList;
        string strCultureCode    = ucUICultureCode;
        string strSchedSysPath   = Util._SysPath + "/dhtmlxScheduler/";

        Util.setJS(Util.getFixURL(strSchedSysPath + "dhtmlxscheduler.js"), "dhtmlx_JS");
        Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_active_links.js"), "dhtmlx_actlink");
        Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_recurring.js"), "dhtmlx_recurring");
        Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_minical.js"), "dhtmlx_minical");

        if (ucIsToolTip)
        {
            Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_tooltip.js"), "dhtmlx_tooltip");
        }

        if (ucIsYearView)
        {
            Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_year_view.js"), "dhtmlx_yearview");
        }

        Util.setCSS(Util.getFixURL(strSchedSysPath + "dhtmlxscheduler.css"));

        //判斷顯示語系
        switch (strCultureCode)
        {
        case "zh-CHT":
            Util.setJS(Util.getFixURL(strSchedSysPath + "locale/locale_tw.js"), "dhtmlx_Loc01");
            Util.setJS(Util.getFixURL(strSchedSysPath + "locale/recurring/locale_recurring_tw.js"), "dhtmlx_Loc02");
            break;

        case "zh-CHS":
        case "zh-Hans":
            Util.setJS(Util.getFixURL(strSchedSysPath + "locale/locale_cn.js"), "dhtmlx_Loc01");
            Util.setJS(Util.getFixURL(strSchedSysPath + "locale/recurring/locale_recurring_cn.js"), "dhtmlx_Loc02");
            break;

        default:
            break;
        }

        string strDataURL = string.Format("{0}?DBName={1}&TableName={2}&IsReadOnly={3}&ResourceIDList={4}&NewColor={5}&NewTextColor={6}", Util.getFixURL(strSchedSysPath + "SchedulerHandler.ashx"), ucDBName, ucTableName, (ucIsReadOnly == true) ? "Y" : "N", strResourceIDList, ucNewEventColor, ucNewEventTextColor);

        Util.setJSContent("");

        StringBuilder sb = new StringBuilder();

        sb.Append("\nfunction init() { \n"
                  + "    scheduler.config.xml_date = '%Y-%m-%d %H:%i'; \n");
        sb.AppendFormat("    scheduler.config.first_hour = {0}; \n", ucFirstHour);
        sb.AppendFormat("    scheduler.config.last_hour = {0}; \n", ucLastHour);
        sb.AppendFormat("    scheduler.config.time_step = {0}; \n", ucTimeStep);
        sb.AppendFormat("    scheduler.config.start_on_monday = {0}; \n", ucIsStartOnMonday ? 1 : 0);
        sb.AppendFormat("    scheduler.config.event_duration = {0}; \n", ucEventDuration);
        sb.Append("    scheduler.config.auto_end_date = true; \n"
                  + "    scheduler.config.details_on_create = true;\n"
                  + "    scheduler.config.details_on_dblclick = true;\n");

        sb.Append("    scheduler.config.lightbox.sections=[\n"
                  + "    {name:'text'   , height:24 ,  map_to:'text'   , type:'textarea' , focus:true },\n"
                  + "    {name:'description' , height:200, map_to:'description' , type:'textarea' },\n"
                  + "    {name:'recurring',type:'recurring',map_to:'rec_type',button:'recurring'},\n"
                  + "    {name:'time'   , height:72 , map_to:'auto'   , type:'time' }\n"
                  + "    ];\n");


        ResourceInfo oRS = new ResourceInfo();

        switch (strCultureCode)
        {
        case "en":
            oRS = new ResourceInfo()
            {
                ResourceID        = "Source :",
                Subject           = "Subject:",
                Description       = "Desc.  :",
                StartDate         = "Start  :",
                EndDate           = "End    :",
                UpdInfo           = "Update :",
                Msg_EventConflict = "Event Collision !",
                Msg_NotEventOwner = "Not Event Owner !"
            };
            break;

        case "zh-CHT":
        case "zh-Hant":
            oRS = new ResourceInfo()
            {
                ResourceID        = "識別:",
                Subject           = "主旨:",
                Description       = "描述:",
                StartDate         = "開始:",
                EndDate           = "結束:",
                UpdInfo           = "更新:",
                Msg_EventConflict = "該時段已有事件存在 !",
                Msg_NotEventOwner = "無權編修此事件 !"
            };
            break;

        case "zh-CHS":
        case "zh-Hans":
            oRS = new ResourceInfo()
            {
                ResourceID        = "识别:",
                Subject           = "主旨:",
                Description       = "描述:",
                StartDate         = "开始:",
                EndDate           = "结束:",
                UpdInfo           = "更新:",
                Msg_EventConflict = "该时段已有事件存在!",
                Msg_NotEventOwner = "无权编修此事件!"
            };
            break;
        }

        if (ucIsToolTip)
        {
            sb.Append("    scheduler.templates.tooltip_text = function(start,end,ev){{");
            sb.AppendFormat("    return '<b>{0}</b> '+ ev.text ", oRS.Subject);

            if (ucIsShowEventDetail)
            {
                sb.AppendFormat("    + '<br/><b>{0}</b> ' + ev.description ", oRS.Description);
            }

            if (ucIsShowEventID)
            {
                sb.AppendFormat("    + '<hr/><b>{0}</b> [' + ev.ResourceID + ']' ", oRS.ResourceID);
            }

            sb.AppendFormat("    + '<br/><b>{0}</b> ' + scheduler.templates.tooltip_date_format(start) ", oRS.StartDate);

            sb.AppendFormat("    + '<br/><b>{0}</b> ' + scheduler.templates.tooltip_date_format(end)", oRS.EndDate);
            if (ucIsShowEventUpdInfo)
            {
                sb.AppendFormat("    + '<br/><b>{0}</b> ' + ev.UpdDateTime.substr(0, 16) + ' By ' + ev.UpdUser + ' - ' + ev.UpdUserName ", oRS.UpdInfo);
            }
            sb.Append(" ;}};\n");
        }

        if (!ucIsShowEventTime)
        {
            sb.Append("scheduler.templates.event_date = function(start,end,ev){ return '' ;}; \n");
        }

        if (!ucIsNavBar)
        {
            sb.Append("    scheduler.xy.nav_height = 0;\n");
            dhx_cal_navline.Style["display"] = "none";
        }

        if (!ucIsMiniCalEnabled)
        {
            dhx_minical_icon.Style["display"] = "none";
        }

        if (ucIsYearView)
        {
            sb.Append("    document.getElementById('yearView').style.display = '';\n");
        }

        if (ucIsMiniCalOnly)
        {
            mini_here.Style["display"]      = "";
            scheduler_here.Style["display"] = "none";
            sb.AppendFormat("    scheduler.load('{0}&Rnd={1}' ,", strDataURL, Util.getRandomNum(10000, 99999)[0]);
            sb.Append("    function(){  scheduler.renderCalendar({\n"
                      + "    container:'mini_here',date:scheduler._date,navigation:true,handler:function(date,calendar){ \n"
                      );
            //在獨立的小日曆按下日期後的動作
            if (ucIsMiniCalToScheduler)
            {
                string strScheUrl = strScheUrl = string.Format("{0}?DBName={1}&TableName={2}&ResourceIDList={3}&IsReadOnly={4}&LoadMode={5}&Width={6}&Height={7}", Util.getFixURL("~/Util/SchedulerAdmin.aspx"), ucDBName, ucTableName, ucResourceIDList, (ucIsReadOnly == true) ? "Y" : "N", ucLoadMode, ucWidth, ucHeight);

                strScheUrl += string.Format("&IsShowEventDetail={0}&IsShowEventTime={1}&IsShowEventID={2}&IsShowEventUpdInfo={3}&IsConflictEnabled={4}&IsOwnerEditOnly={5}",
                                            (ucIsShowEventDetail) ? "Y" : "N",
                                            (ucIsShowEventTime) ? "Y" : "N",
                                            (ucIsShowEventID) ? "Y" : "N",
                                            (ucIsShowEventUpdInfo) ? "Y" : "N",
                                            (ucIsConflictEnabled) ? "Y" : "N",
                                            (ucIsOwnerEditOnly) ? "Y" : "N"
                                            );


                sb.Append("var PopUrl  = '" + strScheUrl + "&LoadDate=' + date.getFullYear() + ',' + date.getMonth() + ',' + date.getDate(); \n");
                string strSchePop = string.Format("var {0}_Pop=window.open(PopUrl + '&Caption={1}','{0}_PopWin','{2}');{0}_Pop.focus();return false;", "ScheAdmin", ucCaption, Util.getAppSetting("app://CfgPopupSpecs/"));
                sb.Append(strSchePop);
            }
            else
            {
                sb.Append("  alert('Selected ScheDate = [' + date.getFullYear() + ',' + date.getMonth() + ',' +  date.getDate() + ']'); \n");
            }

            sb.Append("      }\n"
                      + "    });\n"
                      + " });\n"
                      );
        }
        else
        {
            mini_here.Style["display"]      = "none";
            scheduler_here.Style["display"] = "";
            sb.AppendFormat("    scheduler.load('{0}&Rnd={1}');\n", strDataURL, Util.getRandomNum(10000, 99999)[0]);
        }

        if (ucIsReadOnly == true || strResourceIDList.Split(',').Length > 1)    // 只要 ResourceID 數量大於1 即為唯讀
        {
            //當 [唯讀] 或 [多個 ResourceID]
            Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_readonly.js"), "dhtmlx_readonly");
            sb.Append("    scheduler.config.drag_move = false;\n");

            //2015.11.26 add [ucIsShowReadOnlyForm]
            if (ucIsShowReadOnlyForm)
            {
                sb.Append("    scheduler.config.readonly = false;\n");
                sb.Append("    scheduler.config.readonly_form = true;\n");
            }
            else
            {
                sb.Append("    scheduler.config.readonly = true;\n");
                sb.Append("    scheduler.config.readonly_form = false;\n");
            }


            sb.Append("    scheduler.attachEvent('onEmptyClick', function(date,e) { return false; } ); \n");
            sb.Append("    scheduler.attachEvent('onClick', function(id, e) { return false; } ); \n");
        }
        else
        {
            //可編輯
            //Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_quick_info.js"), "dhtmlx_quickinfo");
            sb.AppendFormat("    var dp = new dataProcessor('{0}&Rnd={1}');\n", strDataURL, Util.getRandomNum(10000, 99999)[0]);
            sb.Append("    dp.init(scheduler);\n");

            //非既有事件 Owner 不能進行修改/刪除
            if (ucIsOwnerEditOnly)
            {
                UserInfo oUser = UserInfo.getUserInfo();
                if (oUser != null && !string.IsNullOrEmpty(oUser.UserID))
                {
                    sb.Append("    scheduler.attachEvent('onClick', function(id, e) {\n"
                              + "       ev = scheduler.getEvent(id); \n"
                              + "       if (ev.UpdUser != undefined && ev.UpdUser != '" + oUser.UserID + "'){ \n"
                              //+ "          alert ('" + oRS.Msg_NotEventOwner +"'); \n"
                              + "          return false; }\n"
                              + "       return true; \n"
                              + "     }); \n");

                    sb.Append("    scheduler.attachEvent('onDblClick', function(id, e) {\n"
                              + "       ev = scheduler.getEvent(id); \n"
                              + "       if (ev.UpdUser != undefined && ev.UpdUser != '" + oUser.UserID + "'){ \n"
                              + "          alert ('" + oRS.Msg_NotEventOwner + "'); \n"
                              + "          return false; }\n"
                              + "       return true; \n"
                              + "     }); \n");

                    sb.Append("    scheduler.attachEvent('onBeforeDrag', function(id, e) {\n"
                              + "       ev = scheduler.getEvent(id); \n"
                              + "       if (ev.UpdUser != undefined && ev.UpdUser != '" + oUser.UserID + "'){ \n"
                              //+ "          alert ('" + oRS.Msg_NotEventOwner + "'); \n"
                              + "          return false; }\n"
                              + "       return true; \n"
                              + "     }); \n");
                }
            }
        }


        //若同時段只允許一個事件
        if (!ucIsConflictEnabled)
        {
            Util.setJS(Util.getFixURL(strSchedSysPath + "ext/dhtmlxscheduler_collision.js"), "dhtmlx_collision");
            sb.Append("    scheduler.attachEvent('onEventCollision', function (ev, evs) { \n"
                      + "       alert('" + oRS.Msg_EventConflict + "'); \n"
                      + "       return true; \n"
                      + "     }); \n");
        }

        sb.Append(" scheduler.config.show_loading = true;\n");
        sb.AppendFormat("    scheduler.init('scheduler_here', new Date({1}), '{0}');\n", ucLoadMode, ucLoadDate);

        sb.Append("} \n"
                  + "window.onload = function () { init(); };\n");

        Util.setJSContent(sb.ToString(), "dhtmlx_Init");

        //-- 切換小月曆的 script
        Util.setJSContent("\nfunction show_minical() {\n"
                          + "    if (scheduler.isCalendarVisible()) {\n"
                          + "        scheduler.destroyCalendar();\n"
                          + "    } else {\n"
                          + "        scheduler.renderCalendar({\n"
                          + "            position: 'dhx_minical_icon',\n"
                          + "            date: scheduler._date,\n"
                          + "            navigation: true,\n"
                          + "            handler: function (date, calendar) {\n"
                          + "                scheduler.setCurrentView(date);\n"
                          + "                scheduler.destroyCalendar()\n"
                          + "            }\n"
                          + "        });\n"
                          + "    }\n"
                          + "}\n", "dhtmlx_showmini");
    }
Ejemplo n.º 51
0
        /* Private members */

        private Gtk.Dialog BuildDialog()
        {
            Gtk.Dialog dialog = new Gtk.Dialog(Catalog.GetString("Headers"), Base.Ui.Window, DialogFlags.Modal | DialogFlagsUseHeaderBar,
                                               Util.GetStockLabel("gtk-cancel"), ResponseType.Cancel, Util.GetStockLabel("gtk-apply"), ResponseType.Ok);

            dialog.DefaultResponse = ResponseType.Ok;
            dialog.DefaultWidth    = WidgetStyles.DialogWidthMedium;
            dialog.DefaultHeight   = WidgetStyles.DialogHeightLarge;

            Notebook notebook = new Notebook();

            notebook.Expand      = true;
            notebook.TabPos      = PositionType.Left;
            notebook.BorderWidth = WidgetStyles.BorderWidthMedium;

            Grid grid;

            //Karaoke Lyrics LRC
            grid = CreatePageWithGrid(notebook, "Karaoke Lyrics LRC");
            grid.Attach(CreateLabel(Catalog.GetString("Title:")), 0, 0, 1, 1);
            grid.Attach(CreateEntry("Title"), 1, 0, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Author:")), 0, 1, 1, 1);
            grid.Attach(CreateEntry("Author"), 1, 1, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Artist:")), 0, 2, 1, 1);
            grid.Attach(CreateEntry("Artist"), 1, 2, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Album:")), 0, 3, 1, 1);
            grid.Attach(CreateEntry("Album"), 1, 3, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("By:")), 0, 4, 1, 1);
            grid.Attach(CreateEntry("FileCreator"), 1, 4, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Version:")), 0, 5, 1, 1);
            grid.Attach(CreateEntry("Version"), 1, 5, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Program:")), 0, 6, 1, 1);
            grid.Attach(CreateEntry("Program"), 1, 6, 1, 1);

            //Karaoke Lyrics VKT
            grid = CreatePageWithGrid(notebook, "Karaoke Lyrics VKT");
            grid.Attach(CreateLabel(Catalog.GetString("Author:")), 0, 0, 1, 1);
            grid.Attach(CreateEntry("Author"), 1, 0, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Source:")), 0, 2, 1, 1);
            grid.Attach(CreateEntry("Source"), 1, 2, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Date:")), 0, 3, 1, 1);
            grid.Attach(CreateEntry("Date"), 1, 3, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Frame Rate:")), 0, 4, 1, 1);
            grid.Attach(CreateEntry("FrameRate"), 1, 4, 1, 1);

            //MPSub
            grid = CreatePageWithGrid(notebook, "MPSub");
            grid.Attach(CreateLabel(Catalog.GetString("Title:")), 0, 0, 1, 1);
            grid.Attach(CreateEntry("Title"), 1, 0, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("File:")), 0, 2, 1, 1);
            grid.Attach(CreateEntry("MPSubFileProperties"), 1, 2, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Author:")), 0, 3, 1, 1);
            grid.Attach(CreateEntry("Author"), 1, 3, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Note:")), 0, 4, 1, 1);
            grid.Attach(CreateEntry("Comment"), 1, 4, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Media Type:")), 0, 5, 1, 1);
            ComboBoxText comboBoxMPSubMediaType = CreateComboBoxText("MPSubMediaType",
                                                                     SubtitleFormatMPSub.HeaderMediaTypeAudio, Catalog.GetString("Audio"),
                                                                     SubtitleFormatMPSub.HeaderMediaTypeVideo, Catalog.GetString("Video"));

            grid.Attach(comboBoxMPSubMediaType, 1, 5, 1, 1);

            //Sub Station Alpha / ASS
            grid = CreatePageWithGrid(notebook, "Sub Station Alpha / ASS");
            grid.Attach(CreateLabel(Catalog.GetString("Title:")), 0, 0, 1, 1);
            grid.Attach(CreateEntry("Title"), 1, 0, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Original Script:")), 0, 1, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaOriginalScript"), 1, 1, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Original Translation:")), 0, 2, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaOriginalTranslation"), 1, 2, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Original Editing:")), 0, 3, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaOriginalEditing"), 1, 3, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Original Timing:")), 0, 4, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaOriginalTiming"), 1, 4, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Original Script Checking:")), 0, 5, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaOriginalScriptChecking"), 1, 5, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Script Updated By:")), 0, 6, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaScriptUpdatedBy"), 1, 6, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Collisions:")), 0, 7, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaCollisions"), 1, 7, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Timer:")), 0, 8, 1, 1);
            grid.Attach(CreateEntry("SubStationAlphaTimer"), 1, 8, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Play Res X:")), 0, 9, 1, 1);
            grid.Attach(CreateSpinButton("SubStationAlphaPlayResX", 0, 10000, 1), 1, 9, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Play Res Y:")), 0, 10, 1, 1);
            grid.Attach(CreateSpinButton("SubStationAlphaPlayResY", 0, 10000, 1), 1, 10, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Play Depth:")), 0, 11, 1, 1);
            grid.Attach(CreateSpinButton("SubStationAlphaPlayDepth", 0, 10000, 1), 1, 11, 1, 1);

            //SubViewer 1
            grid = CreatePageWithGrid(notebook, "SubViewer 1");
            grid.Attach(CreateLabel(Catalog.GetString("Title:")), 0, 0, 1, 1);
            grid.Attach(CreateEntry("Title"), 1, 0, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Author:")), 0, 1, 1, 1);
            grid.Attach(CreateEntry("Author"), 1, 1, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Source:")), 0, 2, 1, 1);
            grid.Attach(CreateEntry("Source"), 1, 2, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Program:")), 0, 3, 1, 1);
            grid.Attach(CreateEntry("Program"), 1, 3, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("File Path:")), 0, 4, 1, 1);
            grid.Attach(CreateEntry("FilePath"), 1, 4, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Delay:")), 0, 5, 1, 1);
            grid.Attach(CreateSpinButton("Delay", 0, 1000000, 1), 1, 5, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("CD Track:")), 0, 6, 1, 1);
            grid.Attach(CreateSpinButton("CDTrack", 1, 1000, 1), 1, 6, 1, 1);

            //SubViewer 2
            grid = CreatePageWithGrid(notebook, "SubViewer 2");
            grid.Attach(CreateLabel(Catalog.GetString("Title:")), 0, 0, 1, 1);
            grid.Attach(CreateEntry("Title"), 1, 0, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Author:")), 0, 1, 1, 1);
            grid.Attach(CreateEntry("Author"), 1, 1, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Source:")), 0, 2, 1, 1);
            grid.Attach(CreateEntry("Source"), 1, 2, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Program:")), 0, 3, 1, 1);
            grid.Attach(CreateEntry("Program"), 1, 3, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("File Path:")), 0, 4, 1, 1);
            grid.Attach(CreateEntry("FilePath"), 1, 4, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Font Name:")), 0, 5, 1, 1);
            grid.Attach(CreateEntry("SubViewer2FontName"), 1, 5, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Font Color:")), 0, 6, 1, 1);
            grid.Attach(CreateEntry("SubViewer2FontColor"), 1, 6, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Font Style:")), 0, 7, 1, 1);
            grid.Attach(CreateEntry("SubViewer2FontStyle"), 1, 7, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Font Size:")), 0, 8, 1, 1);
            grid.Attach(CreateSpinButton("SubViewer2FontSize", 1, 1000, 1), 1, 8, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("Delay:")), 0, 9, 1, 1);
            grid.Attach(CreateSpinButton("Delay", 0, 1000000, 1), 1, 9, 1, 1);
            grid.Attach(CreateLabel(Catalog.GetString("CD Track:")), 0, 10, 1, 1);
            grid.Attach(CreateSpinButton("CDTrack", 1, 1000, 1), 1, 10, 1, 1);

            //Finalize
            dialog.ContentArea.Add(notebook);
            dialog.ContentArea.ShowAll();

            return(dialog);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Dearchive the region embodied in this request.
        /// </summary>
        public void DearchiveRegion()
        {
            int successfulAssetRestores = 0;
            int failedAssetRestores = 0;

            DearchiveScenesInfo dearchivedScenes;

            // We dearchive all the scenes at once, because the files in the TAR archive might be mixed.
            // Therefore, we have to keep track of the dearchive context of all the scenes.
            Dictionary<UUID, DearchiveContext> sceneContexts = new Dictionary<UUID, DearchiveContext>();

            string fullPath = "NONE";
            TarArchiveReader archive = null;
            byte[] data;
            TarArchiveReader.TarEntryType entryType;

            try
            {
                FindAndLoadControlFile(out archive, out dearchivedScenes);

                while ((data = archive.ReadEntry(out fullPath, out entryType)) != null)
                {
                    //m_log.DebugFormat(
                    //    "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
                    
                    if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
                        continue;


                    // Find the scene that this file belongs to

                    Scene scene;
                    string filePath;
                    if (!dearchivedScenes.GetRegionFromPath(fullPath, out scene, out filePath))
                        continue;   // this file belongs to a region that we're not loading

                    DearchiveContext sceneContext = null;
                    if (scene != null)
                    {
                        if (!sceneContexts.TryGetValue(scene.RegionInfo.RegionID, out sceneContext))
                        {
                            sceneContext = new DearchiveContext(scene);
                            sceneContexts.Add(scene.RegionInfo.RegionID, sceneContext);
                        }
                    }


                    // Process the file

                    if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
                    {
                        sceneContext.SerialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
                    }
                    else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
                    {
                        if (LoadAsset(filePath, data))
                            successfulAssetRestores++;
                        else
                            failedAssetRestores++;

                        if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
                            m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
                    }
                    else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
                    {
                        LoadTerrain(scene, filePath, data);
                    }
                    else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
                    {
                        LoadRegionSettings(scene, filePath, data, dearchivedScenes);
                    } 
                    else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH))
                    {
                        sceneContext.SerialisedParcels.Add(Encoding.UTF8.GetString(data));
                    } 
                    else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
                    {
                        // Ignore, because we already read the control file
                    }
                }

                //m_log.Debug("[ARCHIVER]: Reached end of archive");
            }
            catch (Exception e)
            {
                m_log.Error(
                    String.Format("[ARCHIVER]: Aborting load with error in archive file {0} ", fullPath), e);
                m_errorMessage += e.ToString();
                m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
                return;
            }
            finally
            {
                if (archive != null)
                    archive.Close();
            }

            if (!m_skipAssets)
            {
                m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);

                if (failedAssetRestores > 0)
                {
                    m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
                    m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
                }
            }

            foreach (DearchiveContext sceneContext in sceneContexts.Values)
            {
                m_log.InfoFormat("[ARCHIVER]: Loading region {0}", sceneContext.Scene.RegionInfo.RegionName);

                if (!m_merge)
                {
                    m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
                    sceneContext.Scene.DeleteAllSceneObjects();
                }

                try
                {
                    LoadParcels(sceneContext.Scene, sceneContext.SerialisedParcels);
                    LoadObjects(sceneContext.Scene, sceneContext.SerialisedSceneObjects, sceneContext.SceneObjects);
                    
                    // Inform any interested parties that the region has changed. We waited until now so that all
                    // of the region's objects will be loaded when we send this notification.
                    IEstateModule estateModule = sceneContext.Scene.RequestModuleInterface<IEstateModule>();
                    if (estateModule != null)
                        estateModule.TriggerRegionInfoChange();
                }
                catch (Exception e)
                {
                    m_log.Error("[ARCHIVER]: Error loading parcels or objects ", e);
                    m_errorMessage += e.ToString();
                    m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, new List<UUID>(), m_errorMessage);
                    return;
                }
            }

            // Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
            // that users can enter the scene. If we allow the scripts to start in the loop above
            // then they significantly increase the time until the OAR finishes loading.
            Util.FireAndForget(delegate(object o)
            {
                Thread.Sleep(15000);
                m_log.Info("[ARCHIVER]: Starting scripts in scene objects");

                foreach (DearchiveContext sceneContext in sceneContexts.Values)
                {
                    foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
                    {
                        sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
                        sceneObject.ResumeScripts();
                    }

                    sceneContext.SceneObjects.Clear();
                }
            });

            m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");

            m_rootScene.EventManager.TriggerOarFileLoaded(m_requestId, dearchivedScenes.GetLoadedScenes(), m_errorMessage);
        }
Ejemplo n.º 53
0
 private Label CreateLabel(string text)
 {
     return(Util.CreateLabel(text, 0, 0.5f));
 }
Ejemplo n.º 54
0
        public Fish(Fish other, double rndAmount)
        {
            SetupSight();
            Brain = new Neural.Brain(other.Brain);
            Brain.Randomize(rndAmount);
            rndAmount /= 5.0;
            Color      = new Vector4(MathUtil.Clamp(other.Color.X + Util.RndFloat(-(float)rndAmount, (float)rndAmount), 0.0f, 1.0f), MathUtil.Clamp(other.Color.Y + Util.RndFloat(-(float)rndAmount, (float)rndAmount), 0.0f, 1.0f), MathUtil.Clamp(other.Color.Z + Util.RndFloat(-(float)rndAmount, (float)rndAmount), 0.0f, 1.0f), 1.0f);

            //Temp
            var mag = Color.X * Color.X + Color.Y * Color.Y + Color.Z * Color.Z;

            mag   = (float)Math.Sqrt(mag);
            Color = new Vector4(Color.X / mag, Color.Y / mag, Color.Z / mag, Color.W);
            //====

            MeshIndex = Util.RndInt(0, 3);
        }
        public FloorType GetFloorType(Document doc, FloorSlab floor)
        {
            FloorType f = new FilteredElementCollector(doc).OfClass(typeof(FloorType))
                                                            .Where(ft => ft is FloorType)
                                                            .FirstOrDefault(e =>
                                                            {
                                                                CompoundStructure comp = (e as FloorType).GetCompoundStructure();
                                                                if (comp.GetLayerWidth(0) == Util.MmToFoot(floor.Depth))
                                                                {
                                                                    return true;
                                                                }
                                                                return false;

                                                            }) as FloorType;
            if (f != null) return f;
            f = new FilteredElementCollector(doc).OfClass(typeof(FloorType)).FirstOrDefault(e => e.Name == "Generic - 12\"") as FloorType;
            f = f.Duplicate(String.Format("Floor {0} CM", floor.Depth / 10)) as FloorType;
            CompoundStructure compound = f.GetCompoundStructure();
            compound.SetLayerWidth(0, Util.MmToFoot(floor.Depth));
            f.SetCompoundStructure(compound);

            return f;


        }
Ejemplo n.º 56
0
 public NormGradientClipper(double clipNorm)
 {
     Util.EnsureTrue(clipNorm > 0.0, "clip norm should > 0");
     ClipNorm = clipNorm;
 }
        public FamilySymbol GetIShapeBeamFamilySymbol(Document doc, BeamSt Beam, string familyName, BuiltInCategory category)
        {
            FamilySymbol fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .Where(f => f.FamilyName == familyName)
                                                        .FirstOrDefault(f =>
                                                        {
                                                            if (f.LookupParameter("Width").AsDouble() == Util.MmToFoot(Beam.Width) &&
                                                                f.LookupParameter("Height").AsDouble() == Util.MmToFoot(Beam.Depth) &&
                                                                f.LookupParameter("Flange Thickness").AsDouble() == Util.MmToFoot(Beam.FlangeTh) &&
                                                                f.LookupParameter("Web Thickness").AsDouble() == Util.MmToFoot(Beam.WebTh)
                                                                )
                                                            {
                                                                return true;
                                                            }
                                                            return false;
                                                        });

            if (fs != null) return fs;

            Family family = default;
            try
            {
                fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .First(f => f.FamilyName == familyName);
            }
            catch (Exception)
            {
                string directory = $"C:/ProgramData/Autodesk/RVT {revitVersion}/Libraries/US Imperial/Structural Framing/Steel/AISC 14.1/";
                family = OpenFamily(doc, directory, familyName);
                fs = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
            }

            ElementType fs1 = fs.Duplicate(String.Format("I-Beam Custom {0:0}x{1:0}", Beam.Width / 10, Beam.Depth / 10));
            fs1.LookupParameter("Width").Set(Util.MmToFoot(Beam.Width));
            fs1.LookupParameter("Height").Set(Util.MmToFoot(Beam.Depth));
            fs1.LookupParameter("Flange Thickness").Set(Util.MmToFoot(Beam.FlangeTh));
            fs1.LookupParameter("Web Thickness").Set(Util.MmToFoot(Beam.WebTh));
            fs1.LookupParameter("Web Fillet").Set(Util.MmToFoot(0.85 * (Beam.WebTh)));

            return fs1 as FamilySymbol;
        }
        public FamilySymbol GetLShapeBraceFamilySymbol(Document doc, Brace Brace, string familyName, BuiltInCategory category)
        {
            FamilySymbol fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .Where(f => f.FamilyName == familyName)
                                                        .Where(f =>
                                                        {
                                                            if (f.LookupParameter("d").AsDouble() == Util.MmToFoot(Brace.Depth) &&
                                                                f.LookupParameter("b").AsDouble() == Util.MmToFoot(Brace.Width) &&
                                                                f.LookupParameter("t").AsDouble() == Util.MmToFoot(Brace.Thickness)
                                                                ) return true;

                                                            return false;
                                                        }).FirstOrDefault();

            if (fs != null) return fs;

            Family family = default;
            try
            {
                fs = new FilteredElementCollector(doc).OfCategory(category)
                                                        .WhereElementIsElementType()
                                                        .Cast<FamilySymbol>()
                                                        .First(f => f.FamilyName == familyName);
            }
            catch (Exception)
            {
                string directory = $"C:/ProgramData/Autodesk/RVT {revitVersion}/Libraries/US Imperial/Structural Columns/Steel/";
                family = OpenFamily(doc, directory, familyName);
                fs = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
            }

            ElementType fs1 = fs.Duplicate(String.Format($"L-Angle Custom {0:0}x{1:0}", Brace.Width / 10, Brace.Depth / 10));
            fs1.LookupParameter("b").Set(Util.MmToFoot(Brace.Width));
            fs1.LookupParameter("d").Set(Util.MmToFoot(Brace.Depth));
            fs1.LookupParameter("t").Set(Util.MmToFoot(Brace.Thickness));
            fs1.LookupParameter("k").Set(Util.MmToFoot(Brace.Thickness));
            fs1.LookupParameter("x").Set(Util.MmToFoot(0.28 * (Brace.Thickness)));
            fs1.LookupParameter("y").Set(Util.MmToFoot(0.28 * (Brace.Thickness)));

            return fs1 as FamilySymbol;
        }
Ejemplo n.º 59
0
        public void OpenReadOnly(string pFilename)
        {
            using (FileStream stream = new FileStream(pFilename, FileMode.Open, FileAccess.Read))
            {
                BinaryReader reader            = new BinaryReader(stream);
                ushort       MapleSharkVersion = reader.ReadUInt16();
                ushort       mBuild            = MapleSharkVersion;
                byte         mLocale           = 8;
                if (MapleSharkVersion < 0x2000)
                {
                    ushort mLocalPort = reader.ReadUInt16();
                }
                else
                {
                    byte v1 = (byte)((MapleSharkVersion >> 12) & 0xF),
                         v2 = (byte)((MapleSharkVersion >> 8) & 0xF),
                         v3 = (byte)((MapleSharkVersion >> 4) & 0xF),
                         v4 = (byte)((MapleSharkVersion >> 0) & 0xF);
                    Console.WriteLine("Loading MSB file, saved by MapleShark V{0}.{1}.{2}.{3}", v1, v2, v3, v4);

                    if (MapleSharkVersion == 0x2012)
                    {
                        mLocale = (byte)reader.ReadUInt16();
                        mBuild  = reader.ReadUInt16();
                        ushort mLocalPort = reader.ReadUInt16();
                    }
                    else if (MapleSharkVersion == 0x2014)
                    {
                        String mLocalEndpoint  = reader.ReadString();
                        ushort mLocalPort      = reader.ReadUInt16();
                        String mRemoteEndpoint = reader.ReadString();
                        ushort mRemotePort     = reader.ReadUInt16();

                        mLocale = (byte)reader.ReadUInt16();
                        mBuild  = reader.ReadUInt16();
                    }
                    else if (MapleSharkVersion == 0x2015 || MapleSharkVersion >= 0x2020)
                    {
                        String mLocalEndpoint  = reader.ReadString();
                        ushort mLocalPort      = reader.ReadUInt16();
                        String mRemoteEndpoint = reader.ReadString();
                        ushort mRemotePort     = reader.ReadUInt16();

                        mLocale = reader.ReadByte();
                        mBuild  = reader.ReadUInt16();

                        if (MapleSharkVersion >= 0x2021)
                        {
                            String mPatchLocation = reader.ReadString();
                        }
                    }
                    else
                    {
                        MessageBox.Show("I have no idea how to open this MSB file. It looks to me as a version " + string.Format("{0}.{1}.{2}.{3}", v1, v2, v3, v4) + " MapleShark MSB file... O.o?!");
                        return;
                    }
                }

                while (stream.Position < stream.Length)
                {
                    long   timestamp = reader.ReadInt64();
                    int    size      = MapleSharkVersion < 0x2027 ? reader.ReadUInt16() : reader.ReadInt32();
                    ushort opcode    = reader.ReadUInt16();
                    bool   outbound;

                    if (MapleSharkVersion >= 0x2020)
                    {
                        outbound = reader.ReadBoolean();
                    }
                    else
                    {
                        outbound = (size & 0x8000) != 0;
                        size     = (ushort)(size & 0x7FFF);
                    }

                    byte[] buffer = reader.ReadBytes(size);

                    uint preDecodeIV = 0, postDecodeIV = 0;
                    if (MapleSharkVersion >= 0x2025)
                    {
                        preDecodeIV  = reader.ReadUInt32();
                        postDecodeIV = reader.ReadUInt32();
                    }
                    Packet packet = new Packet(buffer);
                    if (outbound)
                    {
                        Parser.parseOutbound(Util.GetEnumObjectByValue <OutboundOpcodes>(opcode), packet);
                    }
                    else
                    {
                        Parser.parseInbound(Util.GetEnumObjectByValue <InboundOpcodes>(opcode), packet, timestamp);
                    }
                }
            }
            Parser.showAllScripts();
            Text = String.Format("Script Generator | Created by MechAviv");
            Console.WriteLine("Loaded file: {0}", pFilename);
        }
Ejemplo n.º 60
0
        private void CallP(int objectId, string assemblyName, string typeName,
                           string methodName, object[] paramList, ref object result)
        {
            if (m_exiting)
            {
                return;
            }
            string objID     = objectId.ToString();
            object typeInst  = null;
            string appDomain = null;

            // assume first argument to be the name of AppDomain
            if (paramList != null && paramList.Length > 0)
            {
                object param = paramList[paramList.Length - 1];
                if (param is string && (appDomain = (string)param).StartsWith(
                        Util.AppDomainPrefix))
                {
                    appDomain = appDomain.Substring(Util.AppDomainPrefix.Length);
                    if (appDomain.Length > 0)
                    {
                        objID = Util.AppDomainPrefix + ":" + appDomain + objID;
                        object[] newParams = new object[paramList.Length - 1];
                        Array.Copy(paramList, 0, newParams, 0, paramList.Length - 1);
                        paramList = newParams;
                    }
                    else
                    {
                        appDomain = null;
                    }
                }
                else
                {
                    appDomain = null;
                }
            }
            lock (((ICollection)m_InstanceMap).SyncRoot) {
                if (m_InstanceMap.ContainsKey(objID))
                {
                    typeInst = m_InstanceMap[objID];
                }
                else if (appDomain != null)
                {
                    AppDomain domain;
                    if (!m_appDomainMap.ContainsKey(appDomain))
                    {
                        domain = AppDomain.CreateDomain(appDomain);
                        CreateBBServerConnection urlConn = (CreateBBServerConnection)domain.
                                                           CreateInstanceAndUnwrap("FwkClient",
                                                                                   "Apache.Geode.Client.FwkClient.CreateBBServerConnection");
                        urlConn.OpenBBServerConnection(ClientProcess.bbUrl);
                        urlConn.SetLogFile(Util.LogFile);
                        Util.Log("Created app domain {0}", domain);
                        m_appDomainMap.Add(appDomain, domain);
                    }
                    else
                    {
                        domain = m_appDomainMap[appDomain];
                        CreateBBServerConnection urlConn = (CreateBBServerConnection)domain.
                                                           CreateInstanceAndUnwrap("FwkClient",
                                                                                   "Apache.Geode.Client.FwkClient.CreateBBServerConnection");
                        urlConn.SetLogFile(Util.LogFile);
                    }
                    try {
                        typeInst = domain.CreateInstanceAndUnwrap(assemblyName, typeName);
                    } catch (Exception e) {
                        Util.Log("Exception thrown for app domain CreateInstanceAndUnwrap : {0} ", e.Message);
                    }
                    if (typeInst != null)
                    {
                        m_InstanceMap[objID] = typeInst;
                    }
                    else
                    {
                        throw new IllegalArgException(
                                  "FATAL: Could not load class with name: " + typeName);
                    }
                }
                else
                {
                    Assembly assmb = null;
                    try {
                        assmb = Assembly.Load(assemblyName);
                    } catch (Exception) {
                        throw new IllegalArgException(
                                  "FATAL: Could not load assembly: " + assemblyName);
                    }
                    typeInst = assmb.CreateInstance(typeName);
                    if (typeInst != null)
                    {
                        m_InstanceMap[objID] = typeInst;
                    }
                    else
                    {
                        throw new IllegalArgException(
                                  "FATAL: Could not load class with name: " + typeName);
                    }
                }
            }
            MethodInfo[] mInfos = typeInst.GetType().GetMethods(
                BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public
                | BindingFlags.NonPublic | BindingFlags.Static
                | BindingFlags.FlattenHierarchy);
            MethodInfo mInfo = null;

            foreach (MethodInfo method in mInfos)
            {
                if (method.Name.Equals(methodName,
                                       StringComparison.CurrentCultureIgnoreCase))
                {
                    ParameterInfo[] prms     = method.GetParameters();
                    int             paramLen = (paramList != null ? paramList.Length : 0);
                    if (paramLen == prms.Length)
                    {
                        mInfo = method;
                    }
                }
            }
            if (mInfo != null)
            {
                Thread currentThread = Thread.CurrentThread;
                lock (((ICollection)UnitThread.GlobalUnitThreads).SyncRoot) {
                    if (!UnitThread.GlobalUnitThreads.ContainsKey(currentThread))
                    {
                        UnitThread.GlobalUnitThreads.Add(currentThread, true);
                    }
                }
                if (result == null)
                {
                    try
                    {
                        mInfo.Invoke(typeInst, paramList);
                    }
                    catch (TargetInvocationException tie)
                    {
                        Util.Log(Util.LogLevel.Error, tie.InnerException.StackTrace.ToString());
                        throw tie;
                    }
                }
                else
                {
                    result = mInfo.Invoke(typeInst, paramList);
                }
                lock (((ICollection)UnitThread.GlobalUnitThreads).SyncRoot) {
                    if (!UnitThread.GlobalUnitThreads.ContainsKey(currentThread))
                    {
                        UnitThread.GlobalUnitThreads.Remove(currentThread);
                    }
                }
            }
            else
            {
                throw new IllegalArgException("FATAL: Could not load function with name: " +
                                              methodName + ", in class: " + typeInst.GetType());
            }
        }