Summary description for Tools
Exemplo n.º 1
0
 public DnaDrawing(int seed)
 {
     this.seed = seed;
     this.tool = new Tools(seed);
     Shapes = new List<DnaShape>();
     SetDirty();
 }
Exemplo n.º 2
0
 public void ChangeTool(int tool)
 {
     if (_editObject != null) {
         _tool = (Tools)tool;
         EditObject (_editObject);
     }
 }
Exemplo n.º 3
0
        public ActionResult EditTag(int id)
        {
            Tools funcs = new Tools();
            PAWA.Models.Tags theTag = funcs.getTag(id);

            return View(theTag);
        }
Exemplo n.º 4
0
 /// <summary>
 /// 执行编译程序
 /// </summary>
 /// <param name="buildcommand">编译语句</param>
 /// <param name="workdirectory">程序工作路径</param>
 /// <param name="buildResult">记录程序运行的结果</param>
 /// <param name="err">输出错误信息</param>
 /// <returns>程序编译结果的日志</returns>
 public string Build(string buildcommand, string workdirectory, out string buildResult,out string err,out string time)
 {
     Tools tools = new Tools();
     string args = "/C" + " " + buildcommand;
     string filename = "cmd.exe";
     string buildLog = "";
     buildLog = tools.BuildProject(filename, args, workdirectory, out err,out time);
     try
     {
         if (buildLog.Contains("BUILD SUCCESSFUL") || buildLog.Contains("已成功生成") ||
             buildLog.Contains("build succeed"))
         {
             buildResult = "successful";
         }
         else
         {
             buildResult = "failed";
         }
         return buildLog;
     }
     catch(Exception ex)
     {
         buildResult = "failed";
         buildLog = ex.Message;
         return buildLog;
     }
 }
Exemplo n.º 5
0
 public void ChangeSize(Tools.Size size)
 {
     DisposeButtons();
     Tools.GameSize = size;
     this.ClientSize = new Size(20 * ((int)Tools.GameSize + 3), 20 * ((int)Tools.GameSize + 3));
     AddButtons();
 }
    public override void OnInspectorGUI()
    {
        if (EditorApplication.isPlayingOrWillChangePlaymode) return;

        GUILayout.Space(10);

        using (new Vertical("box"))
        {
            using (new Horizontal("TE Toolbar"))
            {
                foreach (KeyValuePair<Tools, IDestructionTool> tool in tools)
                {
                    using (new GUIBackgroundColor(tool.Key == CurrentToolKey ? Color.grey : Color.white))
                    {
                        if (GUILayout.Button(tool.Value.Name, "toolbarbutton"))
                        {
                            if (CurrentToolKey != tool.Key)
                            {
                                tools[tool.Key].OnEnable(targets);
                            }

                            CurrentToolKey = tool.Key;

                            break;
                        }
                    }
                }

                GUILayout.FlexibleSpace();
            }

            CurrentSelectedTool.OnInspectorGUI(targets.Cast<BaseDestructable>().ToArray());
        }
    }
Exemplo n.º 7
0
        private void Initialize()
        {
            var assemblyNames = new List<string> { "MirrorSUPINFO.Apps, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" };
            var mirrorModuleType = typeof(MirrorModule);
            Tools = new Tools();

            InitializeNetwork();

            RegisterMessages();

            Modules = new ObservableCollection<MirrorModule>();

            foreach (var assemblyName in assemblyNames)
            {
                var assembly = Assembly.Load(new AssemblyName(assemblyName));

                foreach (var type in assembly.DefinedTypes)
                {
                    if (type.IsSubclassOf(mirrorModuleType))
                    {
                        Modules.Add((MirrorModule)Activator.CreateInstance(type.AsType(), Tools));
                    }
                }
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// 执行检出操作
 /// </summary>
 /// <param name="repositoryPath">svn服务器路径</param>
 /// <param name="workDirectory">工程本地工作路径</param>
 /// <param name="svnPath">本地svn路径</param>
 /// <param name="checkResult">检出操作的结果</param>
 /// <returns>返回检出操作的日志</returns>
 public string CheckOut(string repositoryPath,string workDirectory,out string checkResult,string xmlConfigPath)
 {
     string err;
     string time;
     XmlDao xmlDao = new XmlDao();
     XmlNodeList xmlNodeList=xmlDao.XmlQuery("config/preferences/SvnPath", xmlConfigPath);
     string svnPath=xmlNodeList[0].InnerText;
     using (SvnClient client = new SvnClient())
     {
         Tools tools = new Tools();
         string checkOutLog = "";
         try
         {
             client.CheckOut(new Uri(repositoryPath), workDirectory);
             string args = "checkout " + repositoryPath + " " + workDirectory;
             checkOutLog = tools.BuildProject(svnPath, args, null, out err, out time);
             checkResult = "successful";
             return checkOutLog;
         }
         catch (Exception ex)
         {
             checkResult = " failed";
             checkOutLog = ex.Message;
             return checkOutLog;
         }
     }
 }
Exemplo n.º 9
0
 public static Tool FindTool(Tools tls, string title)
 {
     foreach(Tool tl in tls.tools)
     {
         if (tl.title == title) return tl;
     }
     return null;
 }
Exemplo n.º 10
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (this.FileUpload1.HasFile)
        {
            string SavePath, SaveFile, ImagesFolder = "Images/Flats";
            SavePath = Path.Combine(Request.PhysicalApplicationPath, ImagesFolder);
            SaveFile = Path.Combine(SavePath, this.FileUpload1.FileName);
            //upload
            try
            {
                try
                {
                    this.FileUpload1.SaveAs(SaveFile);
                }
                catch
                {
                    throw;
                }
                OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["RealEstate"].ConnectionString);
                OleDbCommand cmd = new OleDbCommand("INSERT INTO Pictures (FlatID, PictureURL) VALUES ( @FlatID, @PictureURL)", conn);
                cmd.Parameters.Add("FlatID", OleDbType.Integer);
                cmd.Parameters.Add("PictureURL", OleDbType.VarWChar);

                string query = this.Request.QueryString.ToString();
                int index = query.IndexOf('=');
                query = query.Substring(index + 1);
                cmd.Parameters["FlatID"].Value = Convert.ToInt32(query);
                cmd.Parameters["PictureURL"].Value = this.FileUpload1.FileName.ToString().Trim();
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

                //thumb
                Tools t = new Tools();
                t.adaptPicture(this.FileUpload1.FileName.ToString().Trim());
                //end thumb
                this.FileUpload1.Visible = false;
                this.Button1.Visible = false;
                this.Label1.Text = "File Upload Successfully";
                this.Button2.Visible = true;
            }
            catch
            {
                this.Label1.Text = "Upload Failed, Please Try Again";
                this.FileUpload1.Visible = true;
                this.Button1.Visible = true;
                this.Button2.Visible = false;
            }
            finally
            {

            }
        }
        else
        {
            this.Label1.Text = "Please , Choose a file first!";
        }
    }
Exemplo n.º 11
0
 protected override void InitializeCulture()
 {
     base.InitializeCulture();
     Tools t =new Tools();
     if (!t.IsUserLogin(Session))
     {
         Response.Redirect("~/login.aspx?url=" + Request.RawUrl);
     }
 }
Exemplo n.º 12
0
        public string stringOfTags(FormCollection form)
        {
            Tools tool = new Tools();
            string[] Taglist = seperateTags(form["StringTag"]);
            List<int> TagIDs = tool.checkIfTagExists(Taglist);
            string Tagfinal = tool.convertTagsToString(TagIDs);

            return Tagfinal;
        }
Exemplo n.º 13
0
 public void Init(Tools tool)
 {
     this.tool = tool;
     // pick a colour from the image.
     Pixel pix = colours[tool.GetRandomNumber(0, colours.Length - 1)];
     Red = pix.R;
     Green = pix.G;
     Blue = pix.B;
     Alpha = tool.GetRandomNumber(Settings.ActiveAlphaRangeMin, Settings.ActiveAlphaRangeMax);
 }
Exemplo n.º 14
0
 public static void SaveProject(string path, Tools cp)
 {
     try
     {
         Tools myObject = cp;
         XmlSerializer mySerializer = new XmlSerializer(typeof(Tools),new Type[]{typeof(Tool)});
         StreamWriter myWriter = new StreamWriter(path);
         mySerializer.Serialize(myWriter, myObject);
         myWriter.Close();
     }
     catch (Exception ex) { new wException(ex).ShowDialog(); }
 }
Exemplo n.º 15
0
 public static void Initialize()
 {
     gTime = new GameTime();
     map = new Map(new System.Drawing.Bitmap("Bilder/Map.bmp"));
     Player = new Player(new Vector2f(map.TileSize + 30, map.TileSize + 30));
     mons01 = new Monster01("Bilder/Monster.png", new Vector2f(800, 100));
     mons02 = new Monster01("Bilder/Monster.png", new Vector2f(100, 600));
     tool = new Tools("Bilder/Tool1.png", new Vector2f (800, 800));
        // vulkan = new Vulkan("Bilder/Vulkan.png", new Vector2f(500, 500);
     view = new View();
     view.Center = Player.Position;
 }
Exemplo n.º 16
0
  public frmMain()
  {
   int i;
   Stream file  = null;
   String fname = "CreativeModePlus.res.block_icons.",
          bname = "CreativeModePlus.res.brush.size.",
          name;

   Asm.init();
   InitializeComponent();

   MessageBox.Show( "This program saves changes to the world data every time" +
                "\r\nthe region or layer changes in order to save memory.  If" +
                "\r\nyou make changes that you wish to discard, please revert" +
                "\r\nthem using Undo before moving on.",
                    "Please Note", 
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information );

   tools = new Tools( this, mapImage );
   hInst = this;

   for( i = 0; i < 146; i++ )
   {
    if( i != 95 && i != 36 && i != 34 ) // ignore certain block types
    {
     file = Asm.exe.GetManifestResourceStream( fname + i + ".png" );
     name = ( "" + (( BlockNames ) i )).Replace( '_', ' ' );
     cmbBlocks.Add( name, Image.FromStream( file ), i );
     file.Close();

    }

    if( i != 0 && i < 33 )
    {
     file = Asm.exe.GetManifestResourceStream( bname + i + "x" + i + ".png" );
     cmbPaint.Add( "" + i, Image.FromStream( file ), i - 1 );
     file.Close();

    }    
   }

   prev = new Point( -1, -1 );
   prevScrl = Point.Empty;

   cmbBlocks.SelectedIndex = cmbPaint.SelectedIndex = 0;

   prevVal = 62;
   height.SelectedIndex = 62;

   BlockColor.initBlockColors();

  }
Exemplo n.º 17
0
	void Awake()
	{
		if(instance == null)
		{
			instance = this;
		}
		else 
			Destroy(gameObject);

		explosionPoolerScript = GameObject.FindGameObjectWithTag ("ObjectPooler").transform.FindChild ("Explosion Pooler").GetComponent<ObjectPoolerScript> ();
		explosionMiniPoolerScript = GameObject.FindGameObjectWithTag ("ObjectPooler").transform.FindChild ("ExplosionMini Pooler").GetComponent<ObjectPoolerScript> ();

		if(GameObject.FindGameObjectWithTag("PlayerFighter") == null)
		{
			if(playerUI != null)
				playerUI.SetActive(false);

			BGScroller[] scrollers = Camera.main.GetComponentsInChildren<BGScroller>();
			foreach(BGScroller scroller in scrollers)
			{
				scroller.basedOnPlayer = false;
			}
		}


		if (PlayerPrefsManager.GetVibrateKey() == "true")
		{
			allowVibrationThisSession = true;
			allowVibrationToggleSwitch.isOn = true;
		}
		else if(PlayerPrefsManager.GetVibrateKey() == "false")
		{
			allowVibrationThisSession = false;
			allowVibrationToggleSwitch.isOn = false;
		}
		else if(PlayerPrefsManager.GetVibrateKey() == "")
		{
			allowVibrationThisSession = allowVibrationToggleSwitch.isOn;

			if(allowVibrationThisSession)
				PlayerPrefsManager.SetVibrateKey("true");
			else
				PlayerPrefsManager.SetVibrateKey("false");
		}
		else
		{
			print(PlayerPrefsManager.GetVibrateKey());
			Debug.LogError("Vibrate Key wasn't blank, true, or false. Something has set it incorrectly. Resetting..");
			PlayerPrefsManager.SetVibrateKey("");
		}
	}
Exemplo n.º 18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            Database db = new Database();
            DataTable dt0 = db.ExecuteDataTable("select Link from Social");
            if (dt0.Rows.Count > 3)
            {
                Facebook.Attributes.Add("href", dt0.Rows[1][0].ToString());
                Twitter.Attributes.Add("href", dt0.Rows[0][0].ToString());
                Google.Attributes.Add("href", dt0.Rows[2][0].ToString());
                Instagram.Attributes.Add("href", dt0.Rows[3][0].ToString());
            }
            Tools t = new Tools();
            if (t.IsUserLogin(Session))
            {
                Users u = Session["User"] as Users;
                LoadMsg();

                db.AddParameter("@id", u.Id);
                object count = db.ExecuteScalar("select count(*) from msg  where msg.toid=@id and msg.isread=0");
                int tmp;
                if (int.TryParse(count.ToString(), out tmp))
                {
                    if (tmp != 0)
                    {
                        lblMsgCount.InnerText = tmp.ToString();
                    }
                    else
                    {
                        lblMsgCount.InnerHtml = "";
                    }

                }

                UserSesction1.Visible = true;
                UserSection2.Visible = true;
                UserLoginSection1.Visible = false;
            }
            else
            {
                profileLink.Visible = false;
                favLink.Visible = false;
                ProfileLink2.Visible = false;
                FavLink2.Visible = false;

                menu.Attributes["class"] += " extended";
            }

        }
    }
Exemplo n.º 19
0
 public ActionResult EditFolder(FormCollection form, string saveChanges, string cancelChanges)
 {
     Tools toolbelt = new Tools();
     bool SuccessfulMove = toolbelt.moveFolder(WebSecurity.CurrentUserId, form["fid"], form["InFolderID"]);
     bool successfulNameChange = toolbelt.changeFolderName(WebSecurity.CurrentUserId, Convert.ToInt32(form["fid"]), form["FolderName"]);
     string errorMessage = "";
     string redirectUrl = "./../Home/Album?folderID=" + form["InFolderID"];
     if (!SuccessfulMove) { errorMessage += "<ERROR>This Edit Has Failed\nThe folder was not moved</ERROR>"; redirectUrl="./../Home/Album";}
     if (!successfulNameChange) { errorMessage += "<ERROR>This Edit Has Failed\nThe folder name was not changed</ERROR>"; redirectUrl = "./../Home/Album"; }
     ViewBag.UserID = new SelectList(dbContext.Users, "UserID", "UserName", WebSecurity.CurrentUserId);
     ViewBag.FolderID = new SelectList(dbContext.Folders, "FolderID", "FolderName", form["InFolderID"]);
     Response.Redirect(redirectUrl+errorMessage);
     return PartialView();
 }
Exemplo n.º 20
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtTitle.Text))
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"الرجاء اختيار العنوان.\")</SCRIPT>", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtUrl.Text))
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"الرجاء ادخال عنوان الانترنت للفيديو.\")</SCRIPT>", false);
            return;
        }
        Tools t=new Tools();
        string youTubeId = t.GetYouTubeId(txtUrl.Text);
        if (string.IsNullOrWhiteSpace(youTubeId))
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"الرجاء التأكد من عنوان الانترنت للفيديو.\")</SCRIPT>", false);
            return;
        }

        db.AddParameter("@title", txtTitle.Text);
        db.AddParameter("@url", youTubeId);
        db.AddParameter("@lang", ddlLang.SelectedValue);

        if (Request.QueryString["Op"].Equals("Edit"))
        {
            try
            {
                db.AddParameter("@id", Request.QueryString["id"]);
                db.ExecuteNonQuery("Update " + tablename + " Set title=@title,url=@url,lang=@lang where Id=@id");
                ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "alertify.alert('تم التعديل ','تم التعديل بنجاح').set('onok', function(closeEvent){ location.href='" + listpage+"'; } );", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"Error : " + ex.Message + "\")</SCRIPT>", false);
            }

        }
        else if (Request.QueryString["Op"] == "Add")
        {
            db.ExecuteNonQuery("Insert into " + tablename + "(Title,url,lang) Values(@Title,@url,@lang)");
            ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "alertify.alert('تم الاضافة ','تم الاضافة بنجاح').set('onok', function(closeEvent){ location.href='" + listpage + "'; } );", true);
        }
    }
Exemplo n.º 21
0
        public override void Initialize()
        {
            Tools = new Tools();
            _timers = new TbrTimers();

            _timers.Start();

            switch (TShock.Config.StorageType.ToLower())
            {
                case "sqlite":
                    DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", Path.Combine(TShock.SavePath, "TBRData.sqlite")));
                    break;
                case "mysql":
                    try
                    {
                        var host = TShock.Config.MySqlHost.Split(':');
                        DB = new MySqlConnection
                        {
                            ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4}",
                                host[0],
                                host.Length == 1 ? "3306" : host[1],
                                TShock.Config.MySqlDbName,
                                TShock.Config.MySqlUsername,
                                TShock.Config.MySqlPassword
                                )
                        };
                    }
                    catch (MySqlException x)
                    {
                        Log.Error(x.ToString());
                        throw new Exception("MySQL not setup correctly.");
                    }
                    break;
                default:
                    throw new Exception("Invalid storage type.");
            }

            dbManager = new Database(DB);

            ServerApi.Hooks.GameInitialize.Register(this, OnInitialize);
            ServerApi.Hooks.NetGreetPlayer.Register(this, OnGreet);
            ServerApi.Hooks.ServerLeave.Register(this, OnLeave);
            TShockAPI.Hooks.PlayerHooks.PlayerPostLogin += PostLogin;
        }
Exemplo n.º 22
0
    void Update ()
    {
        if (Input.GetKeyDown("1"))
            selectedTool = Tools.HAND;
        if (Input.GetKeyDown("2"))
            selectedTool = Tools.FOOD;
        
        if (Input.GetMouseButtonDown(0))
        {
            mouseDown = true;
            downPosition = Input.mousePosition;
            lastMousePos = Input.mousePosition;
        }
        if (Input.GetMouseButtonUp(0))
        {
            mouseDown = false;
            lastMousePos = Input.mousePosition;

            Vector3 mouseDelta = Input.mousePosition -downPosition;
            //Debug.Log(mouseDelta);
            if(mouseDelta.magnitude < 10)
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(ray,out hit))
                {
                    switch(selectedTool)
                    {
                        case Tools.HAND:
                            GameObject obj = Instantiate(handPrefab);
                            obj.transform.position = hit.point;
                            CuboidManager.Instance.KickFish(hit.point, 15.0f);
                            break;
                        case Tools.FOOD:
                            CuboidManager.Instance.PullFish(hit.point, 2.5f);
                            CuboidManager.Instance.FeedFish(hit.point);
                            break;
                    }
                }
            }
        }
    }
Exemplo n.º 23
0
 /// <summary>
 /// 执行清理操作
 /// </summary>
 /// <param name="workingDirectory">工程本地工作路径</param>
 /// <param name="svnPath">svn程序的路径</param>
 /// <param name="cleanResult">清理操作的结果</param>
 /// <returns>返回清理操作的日志</returns>
 public string CleanUp(string workingDirectory, string svnPath, out string cleanResult)
 {
     string err;
     string time;
     Tools tools = new Tools();
     string cleanLog = "";
     try
     {
         string args = "cleanup" + " " + workingDirectory;
         cleanLog = tools.BuildProject(svnPath, args, null,out err,out time);
         cleanResult = "successful";
         return cleanLog;
     }
     catch (Exception ex)
     {
         cleanResult = "failed";
         cleanLog = ex.Message;
         return cleanLog;
     }
 }
Exemplo n.º 24
0
    protected void ButtonDeleteRecord_Click(object sender, EventArgs e)
    {
        int FlatID = GetFlatID();

        Tools T = new Tools();
        T.DeleteFilePicture(FlatID);

        OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["RealEstate"].ConnectionString);
        OleDbCommand command = new OleDbCommand();
        command.CommandText = string.Format("DELETE * FROM Flats WHERE FlatID = {0}", FlatID);
        conn.Open();
        command.Connection = conn;
        command.ExecuteNonQuery();

        command.CommandText = string.Format("DELETE * FROM Pictures WHERE FlatID = {0}", FlatID);
        command.ExecuteNonQuery();

        conn.Close();

        Server.Transfer("Catalog.aspx");
    }
Exemplo n.º 25
0
    protected void ButtonDeleteRecord_Click(object sender, EventArgs e)
    {
        Image MyImage = (Image)this.DetailsView1.FindControl("Image1");
        Tools T = new Tools();
        string ImageName = MyImage.ImageUrl;
        if (MyImage.ImageUrl != null)
        {
            int index = MyImage.ImageUrl.LastIndexOf('/');
            ImageName = MyImage.ImageUrl.Substring(index + 1);
            T.DeleteFile(ImageName);
        }

        string query = this.Request.QueryString.ToString();
        int CharIndex = query.IndexOf('=');
        query = query.Substring(++CharIndex);
        int FlatID = Convert.ToInt32(query);

        RealStateDSTableAdapters.FlatsTableAdapter A = new RealStateDSTableAdapters.FlatsTableAdapter();
        A.DeletePicture(FlatID, ImageName);

        this.DetailsView1.DataBind();
    }
Exemplo n.º 26
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        string ImagesFolder = "Images/Flats";
        string SavePath;
        string SaveFile;
        if (((FileUpload)this.Wizard1.FindControl("FileUpload1")).HasFile)
        {
            try
            {
                SavePath = Path.Combine(Request.PhysicalApplicationPath, ImagesFolder);
                SaveFile = Path.Combine(SavePath, ((FileUpload)this.Wizard1.FindControl("FileUpload1")).FileName);
                ((Label)this.LabelFileName).Text = this.FileUpload1.FileName.ToString().Trim();
                FileUpload1.SaveAs(SaveFile);
                ((FileUpload)this.Wizard1.FindControl("FileUpload1")).Visible = false;
                this.Button1.Visible = false;
                LabelUpload.Text = "File Uploaded Successfully!";
                LabelUpload.Text += "\n";
                LabelUpload.Text += "To Upload More Pictures Edit Flat Info Link On Your Properties Page would help";

                //Create a Thumb
                Tools t = new Tools();
                bool success = t.adaptPicture(this.FileUpload1.FileName.ToString().Trim());
                if (!success)
                {
                    throw new System.Exception();
                };
            }
            catch (Exception ex)
            {
                LabelUpload.Text = "Failed !";
                LabelUpload.Text += "\n\n";
                LabelUpload.Text += ex.Message;
            }
        }
        else
        {
            LabelUpload.Text = "Please, Choose A File First";
        }
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string URL = ((ImageButton)this.GridView1.SelectedRow.Cells[2].Controls[1]).ImageUrl.ToString();
        string FlatID = ((Label)this.GridView1.SelectedRow.Cells[0].Controls[1]).Text.ToString();
        Convert.ToInt32(FlatID);

        Tools T = new Tools();
        T.DeleteFilePicture(Convert.ToInt32(FlatID));

        OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["RealEstate"].ConnectionString);
        OleDbCommand cmd = new OleDbCommand();

        conn.Open();
        cmd.Connection = conn;
        cmd.CommandText = String.Format("DELETE * FROM Flats WHERE FlatID = {0}", FlatID);
        cmd.ExecuteNonQuery();

        cmd.CommandText = String.Format("DELETE * FROM Pictures WHERE FlatID = {0}", FlatID);
        cmd.ExecuteNonQuery();
        conn.Close();

        Server.Transfer("Owner Property.aspx");
    }
Exemplo n.º 28
0
    protected void btnSendMsg_OnClick(object sender, EventArgs e)
    {
        if(ValidateData())
        {
            string baseClass = "alert msgBox text-center";
            Tools t = new Tools();
            Users u=t.GetUser(Session);
            object userId = DBNull.Value;
            if (u != null)
            {
                userId = u.Id;
            }
            Database db=new Database();
            db.AddParameter("@from", userId);
            db.AddParameter("@title", txtTitle.Text);
            db.AddParameter("@msg", txtMsg.Text);
            db.ExecuteNonQuery("insert into msg([from],title,msg) values(@from,@title,@msg)");
            msg.CssClass = baseClass + " alert-success";
            msg.Visible = true;
            lblMsg.Text = "تم ارسال الرسالة بنجاح";

        }
    }
Exemplo n.º 29
0
 public override void FillInformation(out string summary, out string info, out string detailed) //V
 {
     summary = EventTypeStr.SplitCapsWord();
     info = Tools.FieldBuilder("Captain:" , Captain);
     detailed = "";
 }
Exemplo n.º 30
0
        private void GetCustomers()
        {
            _customers = _dataProvider.GetCustomers();

            Tools.Add(new CustomerDetailsViewModel(_dataProvider, "ALFKI"));
        }
Exemplo n.º 31
0
        public void Download()
        {
            int       counter  = 0;
            DataTable dtResult = new DataTable();

            int result  = 0;
            int result2 = 0;

            using (Database db = new Database())
            {
                Guid _RowID;

                db.Commands.Add(db.CreateCommand("usp_Harga_Promo_Download"));
                foreach (DataRow dr in dtHPromo.Rows)
                {
                    //add parameters
                    _RowID = Guid.NewGuid();


                    db.Commands[0].Parameters.Clear();
                    db.Commands[0].Parameters.Add(new Parameter("@RowID", SqlDbType.UniqueIdentifier, _RowID));
                    db.Commands[0].Parameters.Add(new Parameter("@idrec", SqlDbType.VarChar, Tools.isNull(dr["id_brg"], "").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@tmt1", SqlDbType.DateTime, dr["tmt1"]));
                    db.Commands[0].Parameters.Add(new Parameter("@tmt2", SqlDbType.DateTime, dr["tmt2"]));
                    db.Commands[0].Parameters.Add(new Parameter("@id_brg", SqlDbType.VarChar, Tools.isNull(dr["id_brg"], "").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@h_cash", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["h_cash"], "").ToString().Trim())));

                    db.Commands[0].Parameters.Add(new Parameter("@h_top10", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["h_top10"], "").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@h_user", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["h_user"], "").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@het", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["het"], "").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@SyncFlag", SqlDbType.Money, Tools.getBit(dr["id_match"])));
                    db.Commands[0].Parameters.Add(new Parameter("@dcash", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["dcash"], "").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@dtop10", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["dtop10"], "").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@duser", SqlDbType.Money, Convert.ToDecimal(Tools.isNull(dr["duser"], "").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@lastUpdatedBy", SqlDbType.VarChar, SecurityManager.UserID));


                    result = db.Commands[0].ExecuteNonQuery();


                    if (result > 0)
                    {
                        //grid and form status
                        dr["cUploaded"] = true;
                        counter++;
                        progressBar2.Increment(1);
                        lblDownloadStatus1.Text = counter.ToString("#,##0") + "/" + dtHPromo.Rows.Count.ToString("#,##0");
                        this.Refresh();
                        this.Invalidate();
                        Application.DoEvents();
                    }
                }
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Evaluates the Graph Clause by setting up the dataset, applying the pattern and then generating additional bindings if necessary
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <returns></returns>
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            BaseMultiset result;

            //Q: Can we optimise GRAPH when the input is the Null Multiset to just return the Null Multiset?

            if (this._pattern is Bgp && ((Bgp)this._pattern).IsEmpty)
            {
                //Optimise the case where we have GRAPH ?g {} by not setting the Graph and just returning
                //a Null Multiset
                result = new NullMultiset();
            }
            else
            {
                bool datasetOk = false;
                try
                {
                    List <String> activeGraphs = new List <string>();

                    //Get the URIs of Graphs that should be evaluated over
                    if (this._graphSpecifier.TokenType != Token.VARIABLE)
                    {
                        switch (this._graphSpecifier.TokenType)
                        {
                        case Token.URI:
                        case Token.QNAME:
                            Uri activeGraphUri = new Uri(Tools.ResolveUriOrQName(this._graphSpecifier, context.Query.NamespaceMap, context.Query.BaseUri));
                            if (context.Data.HasGraph(activeGraphUri))
                            {
                                //If the Graph is explicitly specified and there are FROM NAMED present then the Graph
                                //URI must be in the graphs specified by a FROM NAMED or the result is null
                                if (context.Query != null &&
                                    ((!context.Query.DefaultGraphs.Any() && !context.Query.NamedGraphs.Any()) ||
                                     context.Query.DefaultGraphs.Any(u => EqualityHelper.AreUrisEqual(activeGraphUri, u)) ||
                                     context.Query.NamedGraphs.Any(u => EqualityHelper.AreUrisEqual(activeGraphUri, u)))
                                    )
                                {
                                    //Either there was no Query OR there were no Default/Named Graphs OR
                                    //the specified URI was either a Default/Named Graph URI
                                    //In any case we can go ahead and set the active Graph
                                    activeGraphs.Add(activeGraphUri.ToString());
                                }
                                else
                                {
                                    //The specified URI was not present in the Default/Named Graphs so return null
                                    context.OutputMultiset = new NullMultiset();
                                    return(context.OutputMultiset);
                                }
                            }
                            else
                            {
                                //If specifies a specific Graph and not in the Dataset result is a null multiset
                                context.OutputMultiset = new NullMultiset();
                                return(context.OutputMultiset);
                            }
                            break;

                        default:
                            throw new RdfQueryException("Cannot use a '" + this._graphSpecifier.GetType().ToString() + "' Token to specify the Graph for a GRAPH clause");
                        }
                    }
                    else
                    {
                        String gvar = this._graphSpecifier.Value.Substring(1);

                        //Watch out for the case in which the Graph Variable is not bound for all Sets in which case
                        //we still need to operate over all Graphs
                        if (context.InputMultiset.ContainsVariable(gvar) && context.InputMultiset.Sets.All(s => s[gvar] != null))
                        {
                            //If there are already values bound to the Graph variable for all Input Solutions then we limit the Query to those Graphs
                            List <Uri> graphUris = new List <Uri>();
                            foreach (ISet s in context.InputMultiset.Sets)
                            {
                                INode temp = s[gvar];
                                if (temp != null)
                                {
                                    if (temp.NodeType == NodeType.Uri)
                                    {
                                        activeGraphs.Add(temp.ToString());
                                        graphUris.Add(((IUriNode)temp).Uri);
                                    }
                                }
                            }
                        }
                        else
                        {
                            //Nothing yet bound to the Graph Variable so the Query is over all the named Graphs
                            if (context.Query != null && context.Query.NamedGraphs.Any())
                            {
                                //Query specifies one/more named Graphs
                                activeGraphs.AddRange(context.Query.NamedGraphs.Select(u => u.ToString()));
                            }
                            else
                            {
                                //Query is over entire dataset/default Graph since no named Graphs are explicitly specified
                                activeGraphs.AddRange(context.Data.GraphUris.Select(u => u.ToSafeString()));
                            }
                        }
                    }

                    //Remove all duplicates from Active Graphs to avoid duplicate results
                    activeGraphs = activeGraphs.Distinct().ToList();

                    //Evaluate the inner pattern
                    BaseMultiset initialInput = context.InputMultiset;
                    BaseMultiset finalResult  = new Multiset();

                    //Evalute for each Graph URI and union the results
                    foreach (String uri in activeGraphs)
                    {
                        //Always use the same Input for each Graph URI and set that Graph to be the Active Graph
                        //Be sure to translate String.Empty back to the null URI to select the default graph
                        //correctly
                        context.InputMultiset = initialInput;
                        Uri currGraphUri = (uri.Equals(String.Empty)) ? null : new Uri(uri);

                        //This bit of logic takes care of the fact that calling SetActiveGraph((Uri)null) resets the
                        //Active Graph to be the default graph which if the default graph is null is usually the Union of
                        //all Graphs in the Store
                        if (currGraphUri == null && context.Data.DefaultGraph == null && context.Data.UsesUnionDefaultGraph)
                        {
                            if (context.Data.HasGraph(null))
                            {
                                context.Data.SetActiveGraph(context.Data[null]);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            context.Data.SetActiveGraph(currGraphUri);
                        }
                        datasetOk = true;

                        //Evaluate for the current Active Graph
                        result = context.Evaluate(this._pattern);

                        //Merge the Results into our overall Results
                        if (result is NullMultiset || result is IdentityMultiset)
                        {
                            //Don't do anything
                        }
                        else
                        {
                            //If the Graph Specifier is a Variable then we must either bind the
                            //variable or eliminate solutions which have an incorrect value for it
                            if (this._graphSpecifier.TokenType == Token.VARIABLE)
                            {
                                String gvar      = this._graphSpecifier.Value.Substring(1);
                                INode  currGraph = (currGraphUri == null) ? null : new UriNode(null, currGraphUri);
                                foreach (int id in result.SetIDs.ToList())
                                {
                                    ISet s = result[id];
                                    if (s[gvar] == null)
                                    {
                                        //If Graph Variable is not yet bound for solution bind it
                                        s.Add(gvar, currGraph);
                                    }
                                    else if (!s[gvar].Equals(currGraph))
                                    {
                                        //If Graph Variable is bound for solution and doesn't match
                                        //current Graph then we have to remove the solution
                                        result.Remove(id);
                                    }
                                }
                            }
                            //Union solutions into the Results
                            finalResult.Union(result);
                        }

                        //Reset the Active Graph after each pass
                        context.Data.ResetActiveGraph();
                        datasetOk = false;
                    }

                    //Return the final result
                    if (finalResult.IsEmpty)
                    {
                        finalResult = new NullMultiset();
                    }
                    context.OutputMultiset = finalResult;
                }
                finally
                {
                    if (datasetOk)
                    {
                        context.Data.ResetActiveGraph();
                    }
                }
            }

            return(context.OutputMultiset);
        }
Exemplo n.º 33
0
        public ActionResult edit(FormCollection collection)
        {
            // Get all the form values
            Int32 id = Convert.ToInt32(collection["txtId"]);
            string user_name = collection["txtUserName"];
            string password = collection["txtPassword"];
            string email = collection["txtEmail"];
            string author_name = collection["txtAuthorName"];
            string author_description = collection["txtAuthorDescription"];
            HttpPostedFileBase authorImage = Request.Files["uploadMainImage"];

            // Modify the author description
            author_description = author_description.Replace(Environment.NewLine, "<br />");

            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC");

            // Get the user
            Administrator user = Administrator.GetOneById(id, domain.front_end_language);

            // Check if the user exists
            if (user == null)
            {
                // Check if the user exists but not are translated
                user = Administrator.GetOneById(id);
                if(user == null)
                {
                    // Create an empty user
                    user = new Administrator();
                }
            }

            // Update values
            user.admin_user_name = user_name;
            user.email = email;
            user.author_name = author_name;
            user.author_description = author_description;

            // Create a error message
            string errorMessage = string.Empty;

            // Get the user on user name
            Administrator userOnUserName = Administrator.GetOneByUserName(user.admin_user_name);

            // Check for errors
            if (userOnUserName != null && user.id != userOnUserName.id)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_unique"), tt.Get("user_name")) + "<br/>";
            }
            if (user.admin_user_name.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("user_name"), "50") + "<br/>";
            }
            if (user.author_name.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "50") + "<br/>";
            }
            if (AnnytabDataValidation.IsEmailAddressValid(user.email) == null)
            {
                errorMessage += "&#149; " + tt.Get("error_email_valid") + "<br/>";
            }
            if (authorImage.ContentLength > 0 && Tools.IsImageJpeg(authorImage) == false)
            {
                errorMessage += "&#149; " + tt.Get("error_invalid_jpeg") + "<br/>";
            }
            if (authorImage.ContentLength > 262144)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_image_size"), "256 kb") + "<br/>"; ;
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Check if we should add or update the user
                if (user.id == 0)
                {
                    // Add the user
                    user.admin_role = "User";
                    Int64 insertId = Administrator.AddMasterPost(user);
                    user.id = Convert.ToInt32(insertId);
                    Administrator.AddLanguagePost(user, domain.front_end_language);
                    Administrator.UpdatePassword(user.id, PasswordHash.CreateHash(password));

                    // Get website settings
                    KeyStringList websiteSettings = WebsiteSetting.GetAllFromCache();
                    string redirectHttps = websiteSettings.Get("REDIRECT-HTTPS");

                    // Create the administrator cookie
                    HttpCookie adminCookie = new HttpCookie("Administrator");
                    adminCookie.Value = Tools.ProtectCookieValue(user.id.ToString(), "Administration");
                    adminCookie.Expires = DateTime.UtcNow.AddDays(1);
                    adminCookie.HttpOnly = true;
                    adminCookie.Secure = redirectHttps.ToLower() == "true" ? true : false;
                    Response.Cookies.Add(adminCookie);
                }
                else
                {
                    // Update the user
                    Administrator.UpdateMasterPost(user);

                    // Update or add the language post
                    if (Administrator.GetOneById(id, domain.front_end_language) != null)
                    {
                        Administrator.UpdateLanguagePost(user, domain.front_end_language);
                    }
                    else
                    {
                        Administrator.AddLanguagePost(user, domain.front_end_language);
                    }
                    

                    // Only update the password if it has changed
                    if (password != "")
                    {
                        Administrator.UpdatePassword(user.id, PasswordHash.CreateHash(password));
                    }
                }

                // Update the image
                if (authorImage.ContentLength > 0)
                {
                    UpdateImage(user.id, authorImage);
                }

                // Redirect the user to the start page
                return RedirectToAction("index");
            }
            else
            {
                // Create the bread crumb list
                List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(3);
                breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/"));
                breadCrumbs.Add(new BreadCrumb(tt.Get("my_pages"), "/user"));
                breadCrumbs.Add(new BreadCrumb(tt.Get("edit") + " " + tt.Get("user_details").ToLower(), "/user/edit"));

                // Set form values
                ViewBag.BreadCrumbs = breadCrumbs;
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.CurrentCategory = new Category();
                ViewBag.CurrentDomain = domain;
                ViewBag.CurrentLanguage = Language.GetOneById(domain.front_end_language);
                ViewBag.TranslatedTexts = tt;
                ViewBag.User = user;
                ViewBag.CultureInfo = Tools.GetCultureInfo(ViewBag.CurrentLanguage);

                // Return the edit view
                return domain.custom_theme_id == 0 ? View("edit") : View("/Views/theme/edit_user_details.cshtml");
            }

        } // End of the edit method
Exemplo n.º 34
0
        public ActionResult edit_rating(FormCollection collection)
        {
            // Make sure that the user is signed in
            Administrator user = Administrator.GetSignedInAdministrator();

            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get the translated texts
            KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC");

            // Check if the post request is valid
            if (user == null || collection == null)
            {
                return RedirectToAction("login", "user");
            }

            // Get the form data
            Int32 post_id = Convert.ToInt32(collection["hiddenPostId"]);
            Int32 language_id = Convert.ToInt32(collection["hiddenLanguageId"]);
            decimal userVote = 0;
            decimal.TryParse(collection["userVote"], NumberStyles.Any, CultureInfo.InvariantCulture, out userVote);

            // Get the post
            Post post = Post.GetOneById(post_id, language_id);

            // Try to get a saved rating
            PostRating postRating = PostRating.GetOneById(post_id, user.id, language_id);

            // Add or update the rating
            if (postRating != null && postRating.administrator_id == user.id)
            {
                // Update values
                postRating.rating_date = DateTime.UtcNow;
                postRating.rating = userVote;

                // Update the rating
                PostRating.Update(postRating);
            }
            else
            {
                // Create a new rating
                postRating = new PostRating();

                // Update values
                postRating.post_id = post_id;
                postRating.administrator_id = user.id;
                postRating.language_id = language_id;
                postRating.rating_date = DateTime.UtcNow;
                postRating.rating = userVote;

                // Add the rating
                PostRating.Add(postRating);
            }

            // Send a email to the administrator of the website
            string subject = tt.Get("rating") + " - " + domain.website_name;
            string message = tt.Get("post") + ": " + postRating.post_id.ToString() + "<br />"
                + tt.Get("language") + ": " + postRating.language_id.ToString() + "<br />"
                + tt.Get("user_name") + ": " + user.admin_user_name + "<br />" 
                + tt.Get("rating") + ": " + postRating.rating.ToString();
            Tools.SendEmailToHost("", subject, message);

            // Update the rating for the post
            Post.UpdateRating(postRating.post_id, postRating.language_id);

            // Redirect the user to the post
            return Redirect("/home/post/" + post.page_name + "#comments");

        } // End of the edit_rating method
Exemplo n.º 35
0
        //下载视频
        public bool Download()
        {
            //开始下载
            delegates.TipText(new ParaTipText(this.Info, "正在分析视频地址"));

            try
            {
                //获取密码
                string password = "";
                if (Info.Url.EndsWith("密码"))
                {
                    password = ToolForm.CreatePasswordForm(true, "", "");
                    Info.Url.Replace("密码", "");
                }

                //取得网页源文件
                string src = Network.GetHtmlSource(Info.Url, Encoding.GetEncoding("GBK"), Info.Proxy);

                //分析视频iid
                string iid = "";

                //取得iid
                Regex rlist = new Regex(@"(a|l)(?<aid>\d+)(i(?<iid>\d+)|)(?=\.html)");
                Match mlist = rlist.Match(Info.Url);
                if (mlist.Success)                 //如果是列表中的视频
                {
                    //尝试取得url中的iid
                    if (!string.IsNullOrEmpty(mlist.Groups["iid"].Value))
                    {
                        iid = mlist.Groups["iid"].Value;
                    }
                    else                        //否则取得源文件中的iid
                    {
                        Regex r1 = new Regex(@"defaultIid = (?<iid>\d+)");
                        Match m1 = r1.Match(src);
                        iid = m1.Groups["iid"].ToString();
                    }
                }
                else                 //如果是普通视频(或新列表视频)
                {
                    //URL中获取id
                    var mIdInUrl = Regex.Match(Info.Url, @"(listplay|albumplay)/(?<l>.+?)/(?<i>.+?)(?=\.html)");
                    if (mIdInUrl.Success)
                    {
                        iid = mIdInUrl.Groups["i"].Value;
                    }
                    else
                    {
                        //2012.08.26 - 08.27修改 albumplay进到这儿的等号两边是没空格的。。
                        var mIdInSrc = Regex.Match(src, @"(listData = |listData=)\[{\niid.+?icode:""(?<icode>[\w\-]+)""", RegexOptions.Singleline);
                        if (mIdInSrc.Success)
                        {
                            iid = mIdInSrc.Groups["icode"].Value;
                        }
                        else
                        {
                            Regex r1 = new Regex(@"(I|i)id = (?<iid>\d+)");
                            Match m1 = r1.Match(src);
                            iid = m1.Groups["iid"].ToString();
                        }
                    }
                }



                //视频地址数组
                string[] videos = null;
                //清空地址
                Info.FilePath.Clear();

                //调用内建的土豆视频解析器
                TudouParser parserTudou = new TudouParser();
                var         pr          = parserTudou.Parse(new ParseRequest()
                {
                    Id = iid, Password = password, Proxy = Info.Proxy, AutoAnswers = Info.AutoAnswer
                });
                videos = pr.ToArray();

                //取得视频标题
                string title = "";
                if (pr.SpecificResult.ContainsKey("title"))
                {
                    title = pr.SpecificResult["title"];
                }
                else
                {
                    //if (mlist.Success)
                    //{
                    //   //取得aid/lid标题
                    //   string aid = mlist.Groups["aid"].Value;
                    //   Regex rlisttitle = null;
                    //   Match mlisttitle = null;
                    //   if (mlist.ToString().StartsWith("a")) //如果是a开头的列表
                    //   {
                    //      rlisttitle = new Regex(@"aid:" + aid + @"\n,name:""(?<title>.+?)""", RegexOptions.Singleline);
                    //      mlisttitle = rlisttitle.Match(src);
                    //   }
                    //   else if (mlist.ToString().StartsWith("l")) //如果是l开头的列表
                    //   {
                    //      rlisttitle = new Regex(@"ltitle = ""(?<title>.+?)""", RegexOptions.Singleline);
                    //      mlisttitle = rlisttitle.Match(src);
                    //   }
                    //   //取得iid标题
                    //   Regex rsubtitle = new Regex(@"iid:" + iid + @"\n(,cartoonType:\d+\n|),title:""(?<subtitle>.+?)""", RegexOptions.Singleline);
                    //   Match msubtitle = rsubtitle.Match(src);
                    //   title = mlisttitle.Groups["title"].Value + "-" + msubtitle.Groups["subtitle"].Value;
                    //}
                    //else
                    //{
                    Regex rTitle = new Regex(@"\<h1\>(?<title>.*)\<\/h1\>");
                    Match mTitle = rTitle.Match(src);
                    title = mTitle.Groups["title"].Value;
                    //}
                }
                Info.Title = title;
                //过滤非法字符
                title = Tools.InvalidCharacterFilter(title, "");

                Info.videos = videos;
                return(true);

                //下载视频
                //确定视频共有几个段落
                Info.PartCount = videos.Length;

                //分段落下载
                for (int i = 0; i < Info.PartCount; i++)
                {
                    Info.CurrentPart = i + 1;

                    //取得文件后缀名
                    string ext = Tools.GetExtension(videos[i]);
                    if (ext == ".f4v")
                    {
                        ext = ".flv";
                    }
                    //设置当前DownloadParameter
                    if (Info.PartCount == 1)                     //如果只有一段
                    {
                        currentParameter = new DownloadParameter()
                        {
                            //文件名 例: c:\123(1).flv
                            FilePath = Path.Combine(Info.SaveDirectory.ToString(),
                                                    title + ext),
                            //文件URL
                            Url = videos[i],
                            //代理服务器
                            Proxy = Info.Proxy
                        };
                    }
                    else                     //如果分段有多段
                    {
                        currentParameter = new DownloadParameter()
                        {
                            //文件名 例: c:\123(1).flv
                            FilePath = Path.Combine(Info.SaveDirectory.ToString(),
                                                    title + "(" + (i + 1).ToString() + ")" + ext),
                            //文件URL
                            Url = videos[i],
                            //代理服务器
                            Proxy = Info.Proxy
                        };
                    }

                    //添加文件路径到List<>中
                    Info.FilePath.Add(currentParameter.FilePath);
                    //下载文件
                    bool success;

                    //提示更换新Part
                    delegates.NewPart(new ParaNewPart(this.Info, i + 1));

                    //下载视频文件
                    success = Network.DownloadFile(currentParameter, this.Info);

                    //下载视频
                    try
                    {
                        success = Network.DownloadFile(currentParameter, this.Info);
                        if (!success)                         //未出现错误即用户手动停止
                        {
                            return(false);
                        }
                    }
                    catch (Exception ex)                     //下载文件时出现错误
                    {
                        //如果此任务由一个视频组成,则报错(下载失败)
                        if (Info.PartCount == 1)
                        {
                            throw ex;
                        }
                        else                         //否则继续下载,设置“部分失败”状态
                        {
                            Info.PartialFinished        = true;
                            Info.PartialFinishedDetail += "\r\n文件: " + currentParameter.Url + " 下载失败";
                        }
                    }
                }

                //下载弹幕(dp)
                if ((Info.DownloadTypes & DownloadType.Subtitle) != 0)
                {
                    try
                    {
                        Network.DownloadFile(new DownloadParameter()
                        {
                            FilePath = Path.Combine(Info.SaveDirectory.ToString(), title + ".json"),
                            Url      = "http://comment.dp.tudou.com/comment/get/" + pr.SpecificResult["iid"] + "/vdn12d/",
                            Proxy    = Info.Proxy
                        });
                    }
                    catch { }
                }
            }
            catch (Exception ex)             //出现错误即下载失败
            {
                throw ex;
            }



            //下载成功完成
            return(true);
        }
Exemplo n.º 36
0
        private void Save(string path, bool xml)
        {
            listMaker1.AlphaSortList();
            listMaker1.BeginUpdate();
            try
            {
                int noA = listMaker1.Count;

                int roundlimit = Convert.ToInt32(numSplitAmount.Value / 2);

                if ((noA % numSplitAmount.Value) <= roundlimit)
                {
                    noA += roundlimit;
                }

                int noGroups =
                    Convert.ToInt32(Math.Round(noA / numSplitAmount.Value));

                int baseIndex  = 0;
                int splitValue = (int)numSplitAmount.Value;
                var articles   = listMaker1.GetArticleList();
                if (xml)
                {
                    string pathPrefix = path.Replace(".xml", " {0}.xml");

                    for (int i = 1; i <= noGroups; i++)
                    {
                        _p.List.ArticleList = articles.GetRange(baseIndex, Math.Min(splitValue, articles.Count));
                        baseIndex          += splitValue;
                        UserPrefs.SavePrefs(_p, string.Format(pathPrefix, i));
                    }
                    MessageBox.Show("Lists Saved to AWB Settings Files");
                }
                else
                {
                    string pathPrefix = path.Replace(".txt", " {0}.txt");
                    for (int i = 1; i <= noGroups; i++)
                    {
                        StringBuilder strList = new StringBuilder();
                        foreach (Article a in articles.GetRange(baseIndex, Math.Min(splitValue, articles.Count)))
                        {
                            strList.AppendLine(a.ToString());
                        }
                        Tools.WriteTextFileAbsolutePath(strList.ToString().TrimEnd(), string.Format(pathPrefix, i),
                                                        false);
                        baseIndex += splitValue;
                    }
                    MessageBox.Show("Lists saved to text files");
                }

                listMaker1.Clear();
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                ErrorHandler.Handle(ex);
            }


            listMaker1.EndUpdate();
        }
Exemplo n.º 37
0
 private void btnQuery_Click(object sender, RoutedEventArgs e)
 {
     LoadReport();
     Tools.ShowMask(true, "正在查找数据,请稍等...");
 }
Exemplo n.º 38
0
 // -------------------------------------------------------------------------------
 // GenerateHash
 // Helper function to generate a hash from the current userName, salt & account name
 // -------------------------------------------------------------------------------
 protected string GenerateHash(string encryptText, string saltText)
 {
     return(Tools.PBKDF2Hash(encryptText, userNameSalt + saltText));
 }
Exemplo n.º 39
0
 public List <RoadFlow.Data.Model.AppLibraryButtons> GetPagerData(out string pager, string query = "", string title = "")
 {
     return(dataAppLibraryButtons.GetPagerData(out pager, query, Tools.GetPageSize(), Tools.GetPageNumber(), title));
 }
Exemplo n.º 40
0
    public static void GetLevelTwelveDictionary(Level currentLevel)
    {
        currentLevel.LevelContainsEmpty = true;
        Dictionary <(int, int), List <Block> > dict = currentLevel.CurrentMap.PointBlockPairs;

        Tools.AddBorder(dict);

        // lava text
        SafeDictionary.Add(dict, (5, 1), new List <Block> {
            new Block.ThingText.TextLava()
        });

        // is text
        SafeDictionary.Add(dict, (6, 1), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // hot text
        SafeDictionary.Add(dict, (7, 1), new List <Block> {
            new Block.SpecialText.TextHot()
        });

        // lava thing
        for (int i = 1; i < 19; i += 1)
        {
            SafeDictionary.Add(dict, (9, i), new List <Block> {
                new Block.Thing.Lava()
            });
        }

        // empty text
        SafeDictionary.Add(dict, (14, 2), new List <Block> {
            new Block.ThingText.TextEmpty()
        });

        // wall text
        SafeDictionary.Add(dict, (1, 9), new List <Block> {
            new Block.ThingText.TextWall()
        });

        // is text
        SafeDictionary.Add(dict, (1, 10), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // stop text
        SafeDictionary.Add(dict, (1, 11), new List <Block> {
            new Block.SpecialText.TextStop()
        });

        // goop text
        SafeDictionary.Add(dict, (18, 3), new List <Block> {
            new Block.ThingText.TextGoop()
        });

        // is text
        SafeDictionary.Add(dict, (18, 4), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // sink text
        SafeDictionary.Add(dict, (18, 5), new List <Block> {
            new Block.SpecialText.TextSink()
        });

        // baba thing
        SafeDictionary.Add(dict, (6, 11), new List <Block> {
            new Block.Thing.Baba()
        });

        // baba text
        SafeDictionary.Add(dict, (5, 14), new List <Block> {
            new Block.ThingText.TextBaba()
        });

        // is text
        SafeDictionary.Add(dict, (6, 14), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // you text
        SafeDictionary.Add(dict, (7, 14), new List <Block> {
            new Block.SpecialText.TextYou()
        });

        // keke text
        SafeDictionary.Add(dict, (12, 13), new List <Block> {
            new Block.ThingText.TextKeke()
        });

        // is text
        SafeDictionary.Add(dict, (13, 13), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // push text
        SafeDictionary.Add(dict, (14, 13), new List <Block> {
            new Block.SpecialText.TextPush()
        });

        // keke thing
        SafeDictionary.Add(dict, (14, 9), new List <Block> {
            new Block.Thing.Keke()
        });

        // wall thing
        SafeDictionary.Add(dict, (16, 9), new List <Block> {
            new Block.Thing.Wall()
        });

        // baba text
        SafeDictionary.Add(dict, (18, 9), new List <Block> {
            new Block.ThingText.TextBaba()
        });

        // is text
        SafeDictionary.Add(dict, (18, 10), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // melt text
        SafeDictionary.Add(dict, (18, 11), new List <Block> {
            new Block.SpecialText.TextMelt()
        });

        // goop thing
        for (int i = 15; i < 19; i += 1)
        {
            SafeDictionary.Add(dict, (i, 15), new List <Block> {
                new Block.Thing.Goop()
            });
        }

        for (int i = 16; i < 19; i += 1)
        {
            SafeDictionary.Add(dict, (15, i), new List <Block> {
                new Block.Thing.Goop()
            });
        }

        // win text
        SafeDictionary.Add(dict, (18, 18), new List <Block> {
            new Block.SpecialText.TextWin()
        });
    }
Exemplo n.º 41
0
 public UTF(Tools tool)
 {
     tools = tool;
 }
Exemplo n.º 42
0
        /// <summary>
        /// 下载视频
        /// </summary>
        public override bool Download()
        {
            //开始下载
            TipText("正在分析视频地址");

            //修正井号
            Info.Url = Info.Url.ToLower().TrimEnd('#');
            //修正旧版URL
            Info.Url = Info.Url.Replace("bilibili.tv", "bilibili.com");
            Info.Url = Info.Url.Replace("bilibili.us", "bilibili.com");
            Info.Url = Info.Url.Replace("bilibili.smgbb.cn", "www.bilibili.com");
            Info.Url = Info.Url.Replace("bilibili.kankanews.com", "www.bilibili.com");

            //修正简写URL
            if (Regex.Match(Info.Url, @"^av\d{2,6}$").Success)
            {
                Info.Url = "http://www.bilibili.com/video/" + Info.Url + "/";
            }
            //修正index_1.html
            if (!Info.Url.EndsWith(".html"))
            {
                if (Info.Url.EndsWith("/"))
                {
                    Info.Url += "index_1.html";
                }
                else
                {
                    Info.Url += "/index_1.html";
                }
            }

            string url = Info.Url;
            //取得子页面文件名(例如"/video/av12345/index_123.html")
            //string suburl = Regex.Match(Info.Url, @"bilibili\.kankanews\.com(?<part>/video/av\d+/index_\d+\.html)").Groups["part"].Value;
            string suburl = Regex.Match(Info.Url, @"www\.bilibili\.com(?<part>/video/av\d+/index_\d+\.html)").Groups["part"].Value;
            //取得AV号和子编号
            //Match mAVNumber = Regex.Match(Info.Url, @"(?<av>av\d+)/index_(?<sub>\d+)\.html");
            Match mAVNumber = BilibiliPlugin.RegexBili.Match(Info.Url);

            if (!mAVNumber.Success)
            {
                mAVNumber = BilibiliPlugin.RegexAcg.Match(Info.Url);
            }
            Settings["AVNumber"]    = mAVNumber.Groups["id"].Value;
            Settings["AVSubNumber"] = mAVNumber.Groups["page"].Value;
            Settings["AVSubNumber"] = string.IsNullOrEmpty(Settings["AVSubNumber"]) ? "1" : Settings["AVSubNumber"];
            //设置自定义文件名
            Settings["CustomFileName"] = BilibiliPlugin.DefaultFileNameFormat;
            if (Info.BasePlugin.Configuration.ContainsKey("CustomFileName"))
            {
                Settings["CustomFileName"] = Info.BasePlugin.Configuration["CustomFileName"];
            }

            //是否通过【自动应答】禁用对话框
            bool disableDialog = AutoAnswer.IsInAutoAnswers(Info.AutoAnswer, "bilibili", "auto");

            //视频地址数组
            string[] videos = null;

            try
            {
                //解析关联项需要同时满足的条件:
                //1.这个任务不是被其他任务所添加的
                //2.用户设置了“解析关联项”
                if (!Info.IsBeAdded || Info.ParseRelated)
                {
                    //取得网页源文件
                    string src      = Network.GetHtmlSource(url, Encoding.UTF8, Info.Proxy);
                    string subtitle = "";
                    //取得子标题
                    Regex           rSubTitle  = new Regex(@"<option value='(?<part>.+?\.html)'( selected)?>(?<content>.+?)</option>");
                    MatchCollection mSubTitles = rSubTitle.Matches(src);

                    //如果存在下拉列表框
                    if (mSubTitles.Count > 0)
                    {
                        //确定当前视频的子标题
                        foreach (Match item in mSubTitles)
                        {
                            if (suburl == item.Groups["part"].Value)
                            {
                                subtitle = item.Groups["content"].Value;
                                break;
                            }
                        }

                        //准备(地址-标题)字典
                        var dict = new Dictionary <string, string>();
                        foreach (Match item in mSubTitles)
                        {
                            if (suburl != item.Groups["part"].Value)
                            {
                                dict.Add(url.Replace(suburl, item.Groups["part"].Value),
                                         item.Groups["content"].Value);
                            }
                        }
                        //用户选择任务
                        var ba = new Collection <string>();
                        if (!disableDialog)
                        {
                            ba = ToolForm.CreateMultiSelectForm(dict, Info.AutoAnswer, "bilibili");
                        }
                        //根据用户选择新建任务
                        foreach (string u in ba)
                        {
                            NewTask(u);
                        }
                    }
                }

                //获取视频信息API
                var ts         = Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds);
                var apiAddress = string.Format(@"http://api.bilibili.cn/view?appkey={0}&ts={1}&id={2}&page={3}",
                                               BilibiliPlugin.AppKey,
                                               ts,
                                               Settings["AVNumber"],
                                               Settings["AVSubNumber"]);
                //AcDown所使用的AppKey是旧AppKey,权限比新申请的要高,而且不需要加上sign验证
                //如果将来要使用sign验证的话可以使用下面的代码来算出sign
                //但是这段代码目前加上后还是不能正确工作的状态,不知道为什么
                //Tools.GetStringHash("appkey=" + BilibiliPlugin.AppKey +
                //					"&id=" + Settings["AVNumber"] +
                //					"&page=" + Settings["AVSubNumber"] +
                //					"&ts=" + ts +
                //					BilibiliPlugin.AppSecret));
                var webrequest = (HttpWebRequest)WebRequest.Create(apiAddress);
                webrequest.Accept    = @"application/json";
                webrequest.UserAgent = "AcDown/" + Application.ProductVersion + " ([email protected])";
                webrequest.Proxy     = Info.Proxy;
                var viewSrc = Network.GetHtmlSource(webrequest, Encoding.UTF8);
                //登录获取API结果
                if (viewSrc.Contains("no perm error"))
                {
                    viewSrc = LoginApi(url, apiAddress, out m_cookieContainer);
                }

                AvInfo avInfo;
                try
                {
                    //解析JSON
                    avInfo = JsonConvert.DeserializeObject <AvInfo>(viewSrc);
                }
                catch
                {
                    //由于接口原因,有时候虽然请求了json但是会返回XML格式(呃
                    var viewDoc = new XmlDocument();
                    viewDoc.LoadXml(viewSrc);
                    avInfo          = new AvInfo();
                    avInfo.title    = viewDoc.SelectSingleNode(@"/info/title").InnerText.Replace("&amp;", "&");
                    avInfo.partname = viewDoc.SelectSingleNode(@"/info/partname").InnerText.Replace("&amp;", "&");
                    avInfo.cid      = Regex.Match(viewSrc, @"(?<=\<cid\>)\d+(?=\</cid\>)", RegexOptions.IgnoreCase).Value;
                }

                //视频标题和子标题
                string title  = avInfo.title ?? "";
                string stitle = avInfo.partname ?? "";

                if (String.IsNullOrEmpty(stitle))
                {
                    Info.Title = title;
                    stitle     = title;
                }
                else
                {
                    Info.Title = title + " - " + stitle;
                }
                //过滤非法字符
                title  = Tools.InvalidCharacterFilter(title, "");
                stitle = Tools.InvalidCharacterFilter(stitle, "");

                //清空地址
                Info.FilePath.Clear();
                Info.SubFilePath.Clear();

                //CID
                Settings["chatid"] = avInfo.cid;

                //下载弹幕
                DownloadComment(title, stitle, Settings["chatid"]);

                //解析器的解析结果
                ParseResult pr = null;

                //如果允许下载视频
                if ((Info.DownloadTypes & DownloadType.Video) != 0)
                {
                    //var playurlSrc = Network.GetHtmlSource(@"http://interface.bilibili.tv/playurl?otype=xml&cid=" + Settings["chatid"] + "&type=flv", Encoding.UTF8);
                    //var playurlDoc = new XmlDocument();
                    //playurlDoc.LoadXml(playurlSrc);

                    //获得视频列表
                    var prRequest = new ParseRequest()
                    {
                        Id              = Settings["chatid"],
                        Proxy           = Info.Proxy,
                        AutoAnswers     = Info.AutoAnswer,
                        CookieContainer = m_cookieContainer
                    };
                    pr     = new BilibiliInterfaceParser().Parse(prRequest);
                    videos = pr.ToArray();

                    //支持导出列表
                    if (videos != null)
                    {
                        StringBuilder sb = new StringBuilder(videos.Length * 2);
                        foreach (string item in videos)
                        {
                            sb.Append(item);
                            sb.Append("|");
                        }
                        if (Settings.ContainsKey("ExportUrl"))
                        {
                            Settings["ExportUrl"] = sb.ToString();
                        }
                        else
                        {
                            Settings.Add("ExportUrl", sb.ToString());
                        }
                    }

                    //下载视频
                    //确定视频共有几个段落
                    Info.PartCount = videos.Length;

                    //------------分段落下载------------
                    for (int i = 0; i < Info.PartCount; i++)
                    {
                        Info.CurrentPart = i + 1;

                        //取得文件后缀名
                        string ext = Tools.GetExtension(videos[i]);
                        if (string.IsNullOrEmpty(ext))
                        {
                            if (string.IsNullOrEmpty(Path.GetExtension(videos[i])))
                            {
                                ext = ".flv";
                            }
                            else
                            {
                                ext = Path.GetExtension(videos[i]);
                            }
                        }
                        if (ext == ".hlv")
                        {
                            ext = ".flv";
                        }

                        //设置文件名
                        var    renamehelper = new CustomFileNameHelper();
                        string filename     = renamehelper.CombineFileName(Settings["CustomFileName"],
                                                                           title, stitle, Info.PartCount == 1 ? "" : Info.CurrentPart.ToString(),
                                                                           ext.Replace(".", ""), Settings["AVNumber"], Settings["AVSubNumber"]);
                        filename = Path.Combine(Info.SaveDirectory.ToString(), filename);

                        //生成父文件夹
                        if (!Directory.Exists(Path.GetDirectoryName(filename)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(filename));
                        }

                        //设置当前DownloadParameter
                        currentParameter = new DownloadParameter()
                        {
                            //文件名 例: c:\123(1).flv
                            FilePath = filename,
                            //文件URL
                            Url = videos[i],
                            //代理服务器
                            Proxy = Info.Proxy,
                            //提取缓存
                            ExtractCache        = Info.ExtractCache,
                            ExtractCachePattern = "fla*.tmp"
                        };

                        //添加文件路径到List<>中
                        Info.FilePath.Add(currentParameter.FilePath);
                        //下载文件
                        bool success;

                        //提示更换新Part
                        delegates.NewPart(new ParaNewPart(this.Info, i + 1));

                        //下载视频
                        try
                        {
                            success = Network.DownloadFile(currentParameter, this.Info);
                            if (!success)                             //未出现错误即用户手动停止
                            {
                                return(false);
                            }
                        }
                        catch                         //下载文件时出现错误
                        {
                            //如果此任务由一个视频组成,则报错(下载失败)
                            if (Info.PartCount == 1)
                            {
                                throw;
                            }
                            else                             //否则继续下载,设置“部分失败”状态
                            {
                                Info.PartialFinished        = true;
                                Info.PartialFinishedDetail += "\r\n文件: " + currentParameter.Url + " 下载失败";
                            }
                        }
                    }            //end for
                }                //end 判断是否下载视频


                //如果插件设置中没有GenerateAcPlay项,或此项设置为true则生成.acplay快捷方式
                if (!Info.BasePlugin.Configuration.ContainsKey("GenerateAcPlay") ||
                    Info.BasePlugin.Configuration["GenerateAcPlay"] == "true")
                {
                    //生成AcPlay文件
                    string acplay = GenerateAcplayConfig(pr, title, stitle);
                    //支持AcPlay直接播放
                    Settings["AcPlay"] = acplay;
                }

                //生成视频自动合并参数
                if (Info.FilePath.Count > 1 && !Info.PartialFinished)
                {
                    Info.Settings.Remove("VideoCombine");
                    var arg = new StringBuilder();
                    foreach (var item in Info.FilePath)
                    {
                        arg.Append(item);
                        arg.Append("|");
                    }

                    var    renamehelper = new CustomFileNameHelper();
                    string filename     = renamehelper.CombineFileName(Settings["CustomFileName"],
                                                                       title, stitle, "",
                                                                       "mp4", Info.Settings["AVNumber"], Info.Settings["AVSubNumber"]);
                    filename = Path.Combine(Info.SaveDirectory.ToString(), filename);

                    arg.Append(filename);
                    Info.Settings["VideoCombine"] = arg.ToString();
                }
            }
            catch
            {
                Settings["user"]     = "";
                Settings["password"] = "";
                throw;
            }

            return(true);
        }
Exemplo n.º 43
0
        public void Download()
        {
            int       counter  = 0;
            DataTable dtResult = new DataTable();
            int       result   = 0;

            using (Database db = new Database())
            {
                // HEADERS

                foreach (DataRow dr in tblHeader.Rows)
                {
                    db.Commands.Clear();
                    db.Commands.Add(db.CreateCommand("usp_OverdueFU_Download_Data"));
                    //add parameters
                    db.Commands[0].Parameters.Clear();
                    db.Commands[0].Parameters.Add(new Parameter("@RowID", SqlDbType.UniqueIdentifier, new Guid()));
                    db.Commands[0].Parameters.Add(new Parameter("@idrec", SqlDbType.VarChar, Tools.isNull(dr["idrec"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@KodeGudang", SqlDbType.VarChar, Tools.isNull(dr["KodeGudang"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@IDKP", SqlDbType.VarChar, Tools.isNull(dr["IDKP"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@KodeToko", SqlDbType.VarChar, Tools.isNull(dr["KodeToko"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@TglTransaksi", SqlDbType.DateTime, dr["TglTrans"]));
                    db.Commands[0].Parameters.Add(new Parameter("@NoTransaksi", SqlDbType.VarChar, Tools.isNull(dr["NoTrans"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@KodeSales", SqlDbType.VarChar, Tools.isNull(dr["KodeSales"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@TglJatuhTempo", SqlDbType.DateTime, dr["TglJT"]));
                    db.Commands[0].Parameters.Add(new Parameter("@RpBayar", SqlDbType.Money, Convert.ToDouble(Tools.isNull(dr["RpBayar"], "0").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@RpSisa", SqlDbType.Money, Convert.ToDouble(Tools.isNull(dr["RpSisa"], "0").ToString().Trim())));

                    db.Commands[0].Parameters.Add(new Parameter("@TglReg", SqlDbType.DateTime, dr["tglreg"]));
                    db.Commands[0].Parameters.Add(new Parameter("@NoReg", SqlDbType.VarChar, Tools.isNull(dr["noreg"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@TglUser", SqlDbType.DateTime, dr["tgluser"]));
                    db.Commands[0].Parameters.Add(new Parameter("@KetUser", SqlDbType.VarChar, Tools.isNull(dr["ketuser"], "0").ToString().Trim()));


                    db.Commands[0].Parameters.Add(new Parameter("@KetAdmin", SqlDbType.VarChar, Tools.isNull(dr["ketadmin"], "0").ToString().Trim()));
                    db.Commands[0].Parameters.Add(new Parameter("@TglUpload ", SqlDbType.DateTime, dr["tglupload"]));
                    db.Commands[0].Parameters.Add(new Parameter("@TglDownld", SqlDbType.DateTime, dr["tgldownld"]));
                    db.Commands[0].Parameters.Add(new Parameter("@Toleransi1", SqlDbType.Int, Convert.ToInt32(Tools.isNull(dr["toleransi1"], "0").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@TglFU", SqlDbType.DateTime, dr["tglfu"]));
                    db.Commands[0].Parameters.Add(new Parameter("@Toleransi2", SqlDbType.Int, Convert.ToInt32(Tools.isNull(dr["toleransi2"], "0").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@TglClose", SqlDbType.DateTime, dr["TglClose"]));
                    db.Commands[0].Parameters.Add(new Parameter("@Toleransi3", SqlDbType.Int, Convert.ToInt32(Tools.isNull(dr["toleransi3"], "0").ToString().Trim())));
                    db.Commands[0].Parameters.Add(new Parameter("@Lclose", SqlDbType.Bit, Tools.getBit(dr["Lclose"])));
                    db.Commands[0].Parameters.Add(new Parameter("@SyncFlag", SqlDbType.Bit, Tools.getBit(dr["SyncFlag"])));
                    db.Commands[0].Parameters.Add(new Parameter("@lastUpdatedBy", SqlDbType.VarChar, SecurityManager.UserID));

                    db.BeginTransaction();

                    result = db.Commands[0].ExecuteNonQuery();
                    if (result >= 0)
                    {
                        dr["cUploaded"] = true;
                        counter++;
                        progressBar1.Increment(1);
                        lblStst.Text = counter.ToString("#,##0") + "/" + tblHeader.Rows.Count.ToString("#,##0");
                        this.Refresh();
                        this.Invalidate();
                        Application.DoEvents();
                    }
                    db.CommitTransaction();
                }
            }
        }
Exemplo n.º 44
0
        private void SetData()
        {
            if (dt.Rows.Count == 0)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    using (Database db = new Database(GlobalVar.DBName))
                    {
                        db.Commands.Add(db.CreateCommand("[usp_InOut_Init]"));
                        db.Commands[0].Parameters.Add(new Parameter("@TahunBulan", SqlDbType.VarChar, Setorans.Year.ToString() + Tools.Right("00" + Setorans.Month.ToString(), 2)));
                        db.Commands[0].ExecuteNonQuery();
                    }
                    LoadData();
                }
                catch (System.Exception ex)
                {
                    Error.LogError(ex);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }

            customGridView1.DataSource = dt;
        }
Exemplo n.º 45
0
        public ActionResult login(FormCollection collection)
        {
            // Get data from the form
            string returnUrl = collection["hiddenReturnUrl"];
            string user_name = collection["txtUserName"];
            string password = collection["txtPassword"];

            // Get the user
            Administrator user = Administrator.GetOneByUserName(user_name);

            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

            // Check if the user exists and if the password is correct
            if (user != null && Administrator.ValidatePassword(user_name, password) == true)
            {
                // Get website settings
                KeyStringList websiteSettings = WebsiteSetting.GetAllFromCache();
                string redirectHttps = websiteSettings.Get("REDIRECT-HTTPS");

                // Create the administrator cookie
                HttpCookie adminCookie = new HttpCookie("Administrator");
                adminCookie.Value = Tools.ProtectCookieValue(user.id.ToString(), "Administration");
                adminCookie.Expires = DateTime.UtcNow.AddDays(1);
                adminCookie.HttpOnly = true;
                adminCookie.Secure = redirectHttps.ToLower() == "true" ? true : false;
                Response.Cookies.Add(adminCookie);

                // Redirect the user to the checkout page
                return Redirect(returnUrl);
            }
            else
            {
                // Create a new user
                user = new Administrator();
                user.admin_user_name = user_name;
                string error_message = "&#149; " + tt.Get("error_login");

                // Create the bread crumb list
                List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(3);
                breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/"));
                breadCrumbs.Add(new BreadCrumb(tt.Get("my_pages"), "/user"));
                breadCrumbs.Add(new BreadCrumb(tt.Get("log_in"), "/user/login"));

                // Set values
                ViewBag.BreadCrumbs = breadCrumbs;
                ViewBag.CurrentCategory = new Category();
                ViewBag.TranslatedTexts = tt;
                ViewBag.CurrentDomain = currentDomain;
                ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
                ViewBag.User = user;
                ViewBag.ErrorMessage = error_message;
                ViewBag.CultureInfo = Tools.GetCultureInfo(ViewBag.CurrentLanguage);

                // Return the login view
                return currentDomain.custom_theme_id == 0 ? View() : View("/Views/theme/user_login.cshtml");
            }

        } // End of the login method
Exemplo n.º 46
0
        private void btnReservar_Click(object sender, EventArgs e)
        {
            try
            {
                ValidateForm();
                var regimen = (Model.Regimen)cbRegimenes.SelectedValue;
                var hotel   = (Model.Hotel)cbHoteles.SelectedValue;

                var totalReserva = Decimal.Parse(txtTotalReserva.Text);

                if (_editObject == null || _editObject.Id == 0)
                {
                    _editObject = new Model.Reserva(0, _session.User, hotel, regimen, _cliente, Tools.GetDate(),
                                                    dtInicio.Value, dtFin.Value, totalReserva, null);
                }
                else
                {
                    _editObject.Hotel        = hotel;
                    _editObject.Regimen      = regimen;
                    _editObject.FechaInicio  = dtInicio.Value;
                    _editObject.FechaFin     = dtFin.Value;
                    _editObject.TotalReserva = totalReserva;
                }
                _editObject.Habitaciones = _habitaciones;

                var codigo = DAO.DAOFactory.ReservaDAO.SaveOrUpdate(_editObject, _session.User, Tools.GetDate());

                string message = "Su reserva ha sido guardada con éxito.\n Su código de reserva es : "
                                 + codigo + ". \nGuardelo para realizar el ingreso al hotel y realizar modificaciones.";
                string            caption = "Reserva " + codigo;
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                var result = MessageBox.Show(message, caption, buttons);
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                string            message = ex.Message;
                string            caption = "Error:";
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                MessageBox.Show(message, caption, buttons);
            }
        }
Exemplo n.º 47
0
    // draw gizmos to help debug the game
    void OnDrawGizmos()
    {
        if (DataController.m_instance == null)
        {
            return;
        }

        // get to the game data
        var gameData = DataController.m_instance.m_gameData;

        // get to the player data
        var playerData = DataController.m_instance.m_playerData;

        // get the current player location
        var location = playerData.m_general.m_location;

        // if we are in hyperspace draw the map grid
        if (location == PD_General.Location.Hyperspace)
        {
            Gizmos.color = Color.green;

            for (var x = 0; x < 250; x += 10)
            {
                var start = Tools.GameToWorldCoordinates(new Vector3(x, 0.0f, 0.0f));
                var end   = Tools.GameToWorldCoordinates(new Vector3(x, 0.0f, 250.0f));

                Gizmos.DrawLine(start, end);
            }

            for (var z = 0; z < 250; z += 10)
            {
                var start = Tools.GameToWorldCoordinates(new Vector3(0.0f, 0.0f, z));
                var end   = Tools.GameToWorldCoordinates(new Vector3(250.0f, 0.0f, z));

                Gizmos.DrawLine(start, end);
            }
        }

        // if we are in hyperspace draw the flux paths
        if (location == PD_General.Location.Hyperspace)
        {
            Gizmos.color = Color.cyan;

            foreach (var flux in gameData.m_fluxList)
            {
                Gizmos.DrawLine(flux.GetFrom(), flux.GetTo());
            }
        }

        // if we are in hyperspace draw the coordinates around the cursor point
        if (location == PD_General.Location.Hyperspace)
        {
            var ray = UnityEditor.HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

            var plane = new Plane(Vector3.up, 0.0f);

            float enter;

            if (plane.Raycast(ray, out enter))
            {
                var worldCoordinates = ray.origin + ray.direction * enter;

                var gameCoordinates = Tools.WorldToGameCoordinates(worldCoordinates);

                UnityEditor.Handles.color = Color.blue;

                UnityEditor.Handles.Label(worldCoordinates + Vector3.forward * 64.0f + Vector3.right * 64.0f, Mathf.RoundToInt(gameCoordinates.x) + "," + Mathf.RoundToInt(gameCoordinates.z));
            }
        }

        // if we are in either hyperspace or a star system then draw the alien encounters
        if ((location == PD_General.Location.StarSystem) || (location == PD_General.Location.Hyperspace))
        {
            // draw the encounter radius
            UnityEditor.Handles.color = Color.red;
            UnityEditor.Handles.DrawWireDisc(playerData.m_general.m_coordinates, Vector3.up, m_encounterRange);

            // draw the radar range
            UnityEditor.Handles.color = Color.magenta;

            if (location == PD_General.Location.Hyperspace)
            {
                UnityEditor.Handles.DrawWireDisc(playerData.m_general.m_coordinates, Vector3.up, m_radar.m_maxHyperspaceDetectionDistance);
            }
            else
            {
                UnityEditor.Handles.DrawWireDisc(playerData.m_general.m_coordinates, Vector3.up, m_radar.m_maxStarSystemDetectionDistance);
            }

            // draw the positions on each encounter
            UnityEditor.Handles.color = Color.red;

            foreach (var pdEncounter in playerData.m_encounterList)
            {
                var encounterLocation = pdEncounter.GetLocation();

                if ((encounterLocation == location) && (location == PD_General.Location.Hyperspace) || (pdEncounter.GetStarId() == playerData.m_general.m_currentStarId))
                {
                    // get access to the encounter
                    var gdEncounter = gameData.m_encounterList[pdEncounter.m_encounterId];

                    // draw alien position
                    UnityEditor.Handles.color = Color.red;
                    UnityEditor.Handles.DrawWireDisc(pdEncounter.m_currentCoordinates, Vector3.up, 16.0f);

                    // print alien race
                    UnityEditor.Handles.Label(pdEncounter.m_currentCoordinates + Vector3.up * 16.0f, gdEncounter.m_race.ToString());

                    // draw the alien radar range
                    UnityEditor.Handles.color = Color.yellow;

                    if (location == PD_General.Location.Hyperspace)
                    {
                        UnityEditor.Handles.DrawWireDisc(pdEncounter.m_currentCoordinates, Vector3.up, m_alienHyperspaceRadarDistance);
                    }
                    else
                    {
                        UnityEditor.Handles.DrawWireDisc(pdEncounter.m_currentCoordinates, Vector3.up, m_alienStarSystemRadarDistance);
                    }
                }
            }
        }
    }
Exemplo n.º 48
0
        // This performs the paste. Returns false when paste was cancelled.
        private bool DoPasteSelection(PasteOptions options)
        {
            // Anything to paste?
            if (Clipboard.ContainsData(CLIPBOARD_DATA_FORMAT))
            {
                // Cancel volatile mode
                General.Editing.DisengageVolatileMode();

                // Let the plugins know
                if (General.Plugins.OnPasteBegin(options))
                {
                    // Ask the editing mode to prepare selection for pasting.
                    if (General.Editing.Mode.OnPasteBegin(options.Copy()))
                    {
                        // Create undo
                        General.MainWindow.DisplayStatus(StatusType.Action, "Pasted selected elements.");
                        General.Map.UndoRedo.CreateUndo("Paste");

                        // Read from clipboard
                        Stream memstream = (Stream)Clipboard.GetData(CLIPBOARD_DATA_FORMAT);
                        memstream.Seek(0, SeekOrigin.Begin);

                        // Mark all current geometry
                        General.Map.Map.ClearAllMarks(true);

                        // Read data stream
                        UniversalStreamReader reader = new UniversalStreamReader();
                        reader.StrictChecking = false;
                        General.Map.Map.BeginAddRemove();
                        reader.Read(General.Map.Map, memstream);
                        General.Map.Map.EndAddRemove();

                        // The new geometry is not marked, so invert the marks to get it marked
                        General.Map.Map.InvertAllMarks();

                        // Convert UDMF fields back to flags and activations, if needed
                        if (!(General.Map.FormatInterface is UniversalMapSetIO))
                        {
                            General.Map.Map.TranslateFromUDMF();
                        }

                        // Modify tags and actions if preferred
                        if (options.ChangeTags == PasteOptions.TAGS_REMOVE)
                        {
                            Tools.RemoveMarkedTags();
                        }
                        if (options.ChangeTags == PasteOptions.TAGS_RENUMBER)
                        {
                            Tools.RenumberMarkedTags();
                        }
                        if (options.RemoveActions)
                        {
                            Tools.RemoveMarkedActions();
                        }

                        // Clean up
                        memstream.Dispose();

                        // Check if anything was pasted
                        int totalpasted = General.Map.Map.GetMarkedThings(true).Count;
                        totalpasted += General.Map.Map.GetMarkedVertices(true).Count;
                        totalpasted += General.Map.Map.GetMarkedLinedefs(true).Count;
                        totalpasted += General.Map.Map.GetMarkedSidedefs(true).Count;
                        totalpasted += General.Map.Map.GetMarkedSectors(true).Count;
                        if (totalpasted > 0)
                        {
                            General.Map.Map.UpdateConfiguration();
                            General.Map.ThingsFilter.Update();
                            General.Editing.Mode.OnPasteEnd(options.Copy());
                            General.Plugins.OnPasteEnd(options);
                        }
                        return(true);
                    }
                }

                // Aborted
                return(false);
            }
            else
            {
                // Nothing usefull on the clipboard
                General.MessageBeep(MessageBeepType.Warning);
                return(false);
            }
        }
Exemplo n.º 49
0
        public async Task<ActionResult> google_login_callback()
        {
            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get the state
            string state = "";
            if (Request.Params["state"] != null)
            {
                state = Server.UrlDecode(Request.Params["state"]);
            }

            // Get the state stored in the session
            string sessionState = "";
            if(Session["GoogleState"] != null)
            {
                sessionState = Session["GoogleState"].ToString();
            }

            // Get the code
            string code = "";
            if (Request.Params["code"] != null)
            {
                code = Server.UrlDecode(Request.Params["code"]);
            }

             // Check if this is a valid callback
            if (state != sessionState || code == "")
            {
                // Redirect the user
                return Redirect("/");
            }

            // Get website settings
            KeyStringList websiteSettings = WebsiteSetting.GetAllFromCache();
            string redirectHttps = websiteSettings.Get("REDIRECT-HTTPS");

            // Get the access token
            string access_token = await AnnytabExternalLogin.GetGoogleAccessToken(domain, code);

            // Get the google user
            Dictionary<string, object> googleUser = await AnnytabExternalLogin.GetGoogleUser(domain, access_token);

            // Get the google data
            string googleId = googleUser.ContainsKey("id") == true ? googleUser["id"].ToString() : "";
            string googleName = googleUser.ContainsKey("displayName") == true ? googleUser["displayName"].ToString() : "";

            // Get the signed in user
            Administrator user = Administrator.GetSignedInAdministrator();

            // Check if the user exists or not
            if (googleId != "" && user != null)
            {
                // Update the user
                user.google_user_id = googleId;
                Administrator.UpdateMasterPost(user);

                // Redirect the user to his start page
                return RedirectToAction("index", "user");
            }
            else if (googleId != "" && user == null)
            {
                // Check if we can find a user with the google id
                user = Administrator.GetOneByGoogleUserId(googleId);

                // Check if the user exists
                if (user == null)
                {
                    // Create a new administrator
                    user = new Administrator();
                    user.admin_user_name = googleId + "_google";
                    user.admin_password = PasswordHash.CreateHash(Tools.GeneratePassword());
                    user.admin_role = "User";
                    user.author_name = "-";
                    user.google_user_id = googleId;

                    // Add the new Administrator
                    Int64 insertId = Administrator.AddMasterPost(user);
                    user.id = Convert.ToInt32(insertId);
                    Administrator.AddLanguagePost(user, domain.front_end_language);
                    Administrator.UpdatePassword(user.id, PasswordHash.CreateHash(user.admin_password));

                    // Create the administrator cookie
                    HttpCookie adminCookie = new HttpCookie("Administrator");
                    adminCookie.Value = Tools.ProtectCookieValue(user.id.ToString(), "Administration");
                    adminCookie.Expires = DateTime.UtcNow.AddDays(1);
                    adminCookie.HttpOnly = true;
                    adminCookie.Secure = redirectHttps.ToLower() == "true" ? true : false;
                    Response.Cookies.Add(adminCookie);

                    // Redirect the user to the edit user page
                    return Redirect("/user/edit");
                }
                else
                {
                    // Create the administrator cookie
                    HttpCookie adminCookie = new HttpCookie("Administrator");
                    adminCookie.Value = Tools.ProtectCookieValue(user.id.ToString(), "Administration");
                    adminCookie.Expires = DateTime.UtcNow.AddDays(1);
                    adminCookie.HttpOnly = true;
                    adminCookie.Secure = redirectHttps.ToLower() == "true" ? true : false;
                    Response.Cookies.Add(adminCookie);

                    // Redirect the user to the start page
                    return RedirectToAction("index");
                }
            }
            else
            {
                // Redirect the user to the login
                return RedirectToAction("login", "user");
            }

        } // End of the google_login_callback method
Exemplo n.º 50
0
 public override void FillInformation(out string summary, out string info, out string detailed) //V
 {
     summary  = EventTypeStr.SplitCapsWord();
     info     = Tools.FieldBuilder("", FriendlyName, "< ; items", Count);
     detailed = "";
 }
Exemplo n.º 51
0
        public ActionResult forgot_password(FormCollection collection)
        {
            // Get form data
            string user_name = collection["txtUserName"];

            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();

            // Get translated texts
            KeyStringList translatedTexts = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

            // Get the user
            Administrator user = Administrator.GetOneByUserName(user_name);

            // Create a random password
            string password = Tools.GeneratePassword();
            
            // Create a error message
            string error_message = "";

            // Check if the user exists
            if(user != null)
            {
                // Create the mail message
                string subject = translatedTexts.Get("forgot") + " " + translatedTexts.Get("password");
                string message = translatedTexts.Get("user_name") + ": " + user.admin_user_name + "<br />" + translatedTexts.Get("password") + ": " + password + "<br />";

                // Try to send the email message
                if(Tools.SendEmailToUser(user.email, subject, message) == false)
                {
                    error_message += "&#149; " + translatedTexts.Get("error_send_email");
                }
            }
            else
            {
                error_message += "&#149; " + translatedTexts.Get("error_user_exists");
            }

            // Check if there is a error message
            if (error_message == "")
            {
                // Update the password
                Administrator.UpdatePassword(user.id, PasswordHash.CreateHash(password));

                // Redirect the user to the login page
                return RedirectToAction("login");
            }
            else
            {
                // Create the bread crumb list
                List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(3);
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("start_page"), "/"));
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("my_pages"), "/user"));
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("forgot") + " " + translatedTexts.Get("password"), "/user/forgot_password"));

                // Set values
                ViewBag.BreadCrumbs = breadCrumbs;
                ViewBag.CurrentCategory = new Category();
                ViewBag.TranslatedTexts = translatedTexts;
                ViewBag.CurrentDomain = currentDomain;
                ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
                ViewBag.User = new Administrator();
                ViewBag.ErrorMessage = error_message;
                ViewBag.CultureInfo = Tools.GetCultureInfo(ViewBag.CurrentLanguage);

                // Return the view
                return currentDomain.custom_theme_id == 0 ? View() : View("/Views/theme/forgot_password.cshtml");
            }

        } // End of the forgot_password method
Exemplo n.º 52
0
 // Use this for initialization
 void Start()
 {
     base.initUI();
     //this.text = Tools.getChild(this.gameObject,"TextBox").GetComponent<Text>();
     this.field = Tools.getChild(this.gameObject, "InputChat").GetComponent <InputField>();
 }
Exemplo n.º 53
0
        void explode(Vector3 force)
        {
            foreach (var item in explodeItemIdList)
            {
                GameObject itemGameObject = GameObjectManager.Instance.Spawn(item);

                var bloodRigidbody = itemGameObject.GetComponent<Rigidbody>();
                var render = itemGameObject.GetComponentInChildren<MeshRenderer>();

                itemGameObject.transform.parent = gameObject.transform.parent;
                itemGameObject.transform.position = gameObject.transform.position + new Vector3(0, 1, 0) + Tools.getRandomVector3(0.2f);

                bloodRigidbody.AddForce(force.normalized * 100.0f + Tools.getRandomVector3(400));

                itemGameObject.DOFade(0, 2).OnComplete(() =>
                {
                    GameObjectManager.Instance.Despawn(itemGameObject);
                });
            }
        }
Exemplo n.º 54
0
		public List<RoadFlow.Data.Model.ShortMessage> GetList(out string pager, int[] status, string query = "", string title = "", string contents = "", string senderID = "", string date1 = "", string date2 = "", string receiveID = "")
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			List<OracleParameter> list = new List<OracleParameter>();
			string value = string.Empty;
			if (status.Length == 1 && status[0] == 0)
			{
				value = "SELECT ID,Title,Contents,SendUserID,SendUserName,ReceiveUserID,ReceiveUserName,SendTime,LinkUrl,LinkID,Type,Files,0 AS Status FROM ShortMessage WHERE 1=1";
			}
			else if (status.Length == 1 && status[0] == 1)
			{
				value = "SELECT ID,Title,Contents,SendUserID,SendUserName,ReceiveUserID,ReceiveUserName,SendTime,LinkUrl,LinkID,Type,Files,1 AS Status FROM ShortMessage1 WHERE 1=1";
			}
			else if (status.Length == 2)
			{
				value = "SELECT * FROM(SELECT ID,Title,Contents,SendUserID,SendUserName,ReceiveUserID,ReceiveUserName,SendTime,LinkUrl,LinkID,Type,Files,0 AS Status FROM ShortMessage WHERE 1=1 UNION ALL SELECT ID,Title,Contents,SendUserID,SendUserName,ReceiveUserID,ReceiveUserName,SendTime,LinkUrl,LinkID,Type,Files,1 AS Status FROM ShortMessage1 WHERE 1=1) temp WHERE 1=1";
			}
			StringBuilder stringBuilder = new StringBuilder(value);
			if (receiveID.IsGuid())
			{
				stringBuilder.Append(" AND ReceiveUserID=:ReceiveUserID");
				list.Add(new OracleParameter(":ReceiveUserID", (object)receiveID));
			}
			if (!title.IsNullOrEmpty())
			{
				stringBuilder.Append(" AND INSTR(Title,:Title,1,1)>0");
				list.Add(new OracleParameter(":Title", (object)title));
			}
			if (!contents.IsNullOrEmpty())
			{
				stringBuilder.Append(" AND INSTR(Contents,:Contents,1,1)>0");
				list.Add(new OracleParameter(":Contents", (object)contents));
			}
			if (!senderID.IsNullOrEmpty())
			{
				stringBuilder.AppendFormat(" AND SendUserID IN({0})", senderID);
			}
			if (date1.IsDateTime())
			{
				stringBuilder.Append(" AND SendTime>=:SendTime");
				list.Add(new OracleParameter(":SendTime", (object)date1.ToDateTime()));
			}
			if (date2.IsDateTime())
			{
				stringBuilder.Append(" AND SendTime<=:SendTime1");
				list.Add(new OracleParameter(":SendTime1", (object)date2.ToDateTime().AddDays(1.0).ToDateString()));
			}
			int pageSize = Tools.GetPageSize();
			int pageNumber = Tools.GetPageNumber();
			long count;
			string paerSql = dbHelper.GetPaerSql(stringBuilder.ToString(), pageSize, pageNumber, out count, list.ToArray());
			pager = Tools.GetPagerHtml(count, pageSize, pageNumber, query);
			OracleDataReader dataReader = dbHelper.GetDataReader(paerSql, list.ToArray());
			List<RoadFlow.Data.Model.ShortMessage> result = DataReaderToList(dataReader);
			((DbDataReader)dataReader).Close();
			return result;
		}
Exemplo n.º 55
0
 private CustomerDetailsViewModel GetCustomerDetailsTool(string customerID)
 {
     return(Tools.OfType <CustomerDetailsViewModel>().FirstOrDefault(c => c.Customer.CustomerID == customerID));
 }
Exemplo n.º 56
0
 private void DomesticActivities_Load(object sender, EventArgs e)
 {
     pictureBoxOK.Image     = Tools.GetIcon(Resources.Ok, 40);
     pictureBoxCancel.Image = Tools.GetIcon(Resources.Cancel, 40);
     comboBoxToesPartially.SelectedIndex = GlobalVar.comboBoxToesPartially;
 }
Exemplo n.º 57
0
        public override void Refresh()
        {
            try
            {
                // create entities
                if (Parent is IEntitySupplier)
                {
                    _entitySupplier = this.Parent as IEntitySupplier;
                }
                if (null != _entitySupplier)
                {
                    // clear factory
                    _factory.Clear();
                    // update factory
                    _entitySupplier.CreateEntities(_factory);
                }

                // get selected tab and compute data accordingly
                switch (tabControlData.SelectedIndex)
                {
                case 0:
                    // compute length
                    PicVisitorDieCutLength visitorLengthes = new PicVisitorDieCutLength();
                    _factory.ProcessVisitor(visitorLengthes);
                    // update controls
                    double lengthCut = 0.0, lengthFold = 0.0;
                    if (visitorLengthes.Lengths.ContainsKey(PicGraphics.LT.LT_CUT))
                    {
                        lengthCut = visitorLengthes.Lengths[PicGraphics.LT.LT_CUT];
                    }

                    lblValueLengthCut.Text = UnitSystem.Instance.CumulativeLength(lengthCut);     //string.Format(": {0:0.###} m", lengthCut / 1000.0);
                    if (visitorLengthes.Lengths.ContainsKey(PicGraphics.LT.LT_CREASING))
                    {
                        lengthFold = visitorLengthes.Lengths[PicGraphics.LT.LT_CREASING];
                    }
                    lblValueLengthFold.Text  = UnitSystem.Instance.CumulativeLength(lengthFold);             //string.Format(": {0:0.###} m", lengthFold / 1000.0);
                    lblValueLengthTotal.Text = UnitSystem.Instance.CumulativeLength(lengthCut + lengthFold); //string.Format(": {0:0.###} m", (lengthCut + lengthFold) / 1000.0);
                    break;

                case 1:
                    // compute bounding box
                    Box2D bbox = Tools.BoundingBox(_factory, 0.0);
                    // update controls
                    lblValueLength.Text = string.Format(": {0:0.#} {1}", bbox.Width, UnitSystem.Instance.UnitLength);
                    lblValueWidth.Text  = string.Format(": {0:0.#} {1}", bbox.Height, UnitSystem.Instance.UnitLength);
                    break;

                case 2:
                    // compute area
                    try
                    {
                        PicToolArea picToolArea = new PicToolArea();
                        _factory.ProcessTool(picToolArea);
                        lblAreaValue.Text = UnitSystem.Instance.Area(picToolArea.Area);    //string.Format(": {0:0.###} m²", (picToolArea.Area * 1.0E-06));

                        lblNameFormat.Visible     = lblValueFormat.Visible = _factory.HasCardboardFormat;
                        lblNameEfficiency.Visible = lblValueEfficiency.Visible = _factory.HasCardboardFormat;

                        if (_factory.HasCardboardFormat)
                        {
                            lblValueFormat.Text     = string.Format(": {0:0.#} x {1:0.#}", _factory.Format.Width, _factory.Format.Height);
                            lblValueEfficiency.Text = string.Format(": {0:0.#} %", 100.0 * picToolArea.Area / (_factory.Format.Width * _factory.Format.Height));
                        }
                    }
                    catch (PicToolTooLongException /*ex*/)
                    {
                        lblAreaValue.Text          = Properties.Resources.ID_ABANDONPROCESSING;
                        lblNameEfficiency.Visible  = false;
                        lblValueEfficiency.Visible = false;
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
Exemplo n.º 58
0
        private void BCreate_Click(object sender, EventArgs e)
        {
            String path     = file.FullName.Replace(file.Name, "");
            String fileName = file.Name.Replace(file.Extension, "") + ".dld";
            String dldFile  = path + fileName;

            // TODO: !IMPLEMENTED: Validation on not filled data - mapped.
            List <MappedValue> inputMappedValues = new List <MappedValue>();

            foreach (DataGridViewRow row in dgvInputMapping.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    if (row.Cells[0].Value.ToString() != "")
                    {
                        MappedValue mappedValue = new MappedValue()
                        {
                            OriginalValue = row.Cells[0].Value.ToString(),
                            NewValue      = row.Cells[1].Value == null ? "" : row.Cells[1].Value.ToString()
                        };

                        inputMappedValues.Add(mappedValue);
                    }
                }
            }

            List <MappedValue> outputMappedValues = new List <MappedValue>();

            foreach (DataGridViewRow row in dgvOutputMapping.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    if (row.Cells[0].Value.ToString() != "")
                    {
                        MappedValue mappedValue = new MappedValue()
                        {
                            OriginalValue = row.Cells[0].Value.ToString(),
                            NewValue      = row.Cells[1].Value == null ? "" : row.Cells[1].Value.ToString()
                        };

                        outputMappedValues.Add(mappedValue);
                    }
                }
            }


            DataLearnDecription dld = new DataLearnDecription()
            {
                InputQuantity            = (int)nudInputQuantity.Value,
                OutputQuantity           = (int)nudOutputQuantity.Value,
                InputPossibleDimensions  = inputPossibleDimensions,
                OutputPossibleDimensions = outputPossibleDimensions,
                InputDimensionIndex      = cbInputDimensions.SelectedIndex,
                OutputDimensionIndex     = cbOutputDimensions.SelectedIndex,
                MappedInputs             = inputMappedValues,
                MappedOutputs            = outputMappedValues
            };

            try
            {
                Tools.SerializeObject(dld, dldFile);
                MessageBox.Show(this, "File " + fileName + " created successfully!", "File created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error while creating dld file: " + ex.Message, "Something went wrong...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 59
0
 public CPK(Tools tool)
 {
     tools = tool;
     isUtfEncrypted = false;
     FileTable = new List<FileEntry>();
 }
Exemplo n.º 60
0
    public static void GetLevelNineDictionary(Level currentLevel)
    {
        currentLevel.LevelContainsEmpty = true;
        Dictionary <(int, int), List <Block> > dict = currentLevel.CurrentMap.PointBlockPairs;

        Tools.AddBorder(dict);

        Tools.AddBlockOfWall(dict, (1, 1), 4);
        Tools.AddBlockOfWall(dict, (15, 1), 4);
        Tools.AddBlockOfWall(dict, (1, 15), 4);
        Tools.AddBlockOfWall(dict, (15, 15), 4);

        // empty text
        SafeDictionary.Add(dict, (7, 3), new List <Block> {
            new Block.ThingText.TextEmpty()
        });

        // is text
        SafeDictionary.Add(dict, (8, 3), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // best text
        SafeDictionary.Add(dict, (3, 8), new List <Block> {
            new Block.ThingText.TextBest()
        });

        // wall text
        SafeDictionary.Add(dict, (18, 8), new List <Block> {
            new Block.ThingText.TextWall()
        });

        // is text
        SafeDictionary.Add(dict, (18, 9), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // stop text
        SafeDictionary.Add(dict, (18, 10), new List <Block> {
            new Block.SpecialText.TextStop()
        });

        // baba text
        SafeDictionary.Add(dict, (4, 12), new List <Block> {
            new Block.ThingText.TextBaba()
        });

        // is text
        SafeDictionary.Add(dict, (5, 12), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // you text
        SafeDictionary.Add(dict, (6, 12), new List <Block> {
            new Block.SpecialText.TextYou()
        });

        // baba thing
        SafeDictionary.Add(dict, (6, 11), new List <Block> {
            new Block.Thing.Baba()
        });

        // ice text
        SafeDictionary.Add(dict, (10, 14), new List <Block> {
            new Block.ThingText.TextIce()
        });

        // is text
        SafeDictionary.Add(dict, (11, 14), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // slip text
        SafeDictionary.Add(dict, (12, 14), new List <Block> {
            new Block.SpecialText.TextSlip()
        });

        // flag text
        SafeDictionary.Add(dict, (7, 18), new List <Block> {
            new Block.ThingText.TextFlag()
        });

        // is text
        SafeDictionary.Add(dict, (8, 18), new List <Block> {
            new Block.SpecialText.TextIs()
        });

        // win text
        SafeDictionary.Add(dict, (9, 18), new List <Block> {
            new Block.SpecialText.TextWin()
        });

        // flag thing
        SafeDictionary.Add(dict, (12, 8), new List <Block> {
            new Block.Thing.Flag()
        });

        // wall thing (middle of canvas)
        for (int i = 10; i < 14; i += 1)
        {
            SafeDictionary.Add(dict, (i, 6), new List <Block> {
                new Block.Thing.Wall()
            });
            SafeDictionary.Add(dict, (i, 13), new List <Block> {
                new Block.Thing.Wall()
            });
        }

        for (int i = 7; i < 10; i += 1)
        {
            SafeDictionary.Add(dict, (10, i), new List <Block> {
                new Block.Thing.Wall()
            });
            SafeDictionary.Add(dict, (13, i), new List <Block> {
                new Block.Thing.Wall()
            });
        }

        SafeDictionary.Add(dict, (13, 14), new List <Block> {
            new Block.Thing.Wall()
        });

        // fake wall
        for (int i = 7; i < 10; i += 1)
        {
            SafeDictionary.Add(dict, (11, i), new List <Block> {
                new Block.Thing.FakeWall()
            });
            if (i != 8)
            {
                SafeDictionary.Add(dict, (12, i), new List <Block> {
                    new Block.Thing.FakeWall()
                });
            }
        }

        // ice thing
        for (int i = 10; i < 13; i += 1)
        {
            for (int j = 10; j < 14; j += 1)
            {
                SafeDictionary.Add(dict, (j, i), new List <Block> {
                    new Block.Thing.Ice()
                });
            }
        }
    }