Archive for Aprile 3rd, 2008

Datagridview Fill

CodeKeep C# Feed Aprile 3rd, 2008

Description: The extra line of code needed to fill up the tableadapter in order for the bindingsource to work

Link: http://www.codekeep.net/snippets/864182cd-333a-4d0f-91df-173537fbac93.aspx

            basicCustomerTableAdapter.Fill(batchSQLDataSet.BasicCustomer);

Logon Database Query

CodeKeep C# Feed Aprile 3rd, 2008

Description: An example of connecting to a database, and checking the username and password.

Link: http://www.codekeep.net/snippets/f362e571-d19a-456a-8849-c124ad7c1a62.aspx

try
            {
                DataSet dsLogon = new DataSet();
                String query = "SELECT [User].FirstName, [User].LastName, Panel, Permission FROM [User], [Role] " +
                               "WHERE " +
                               "Username = '" + txtUsername.Text + "' AND " +
                               "Password = '" + txtPassword.Text + "' AND " +
                               "[User].RoleName = [Role].Name";
                SqlDataAdapter da = new SqlDataAdapter(query, g_obj.getSQLConnection());
                da.Fill(dsLogon, "User");

                if (dsLogon.Tables[0].Rows.Count > 0)
                {
                    // Set permissions to defaults
                    g_obj.gPermissions = new Permissions();

                    // Process all permissions
                    foreach (DataRow row in dsLogon.Tables[0].Rows)
                        g_obj.gPermissions.setPanelPermission(int.Parse(row["Panel"].ToString()),
                                                              int.Parse(row["Permission"].ToString()));

                    String userRealName = dsLogon.Tables[0].Rows[0][0].ToString();
                    userRealName += " " + dsLogon.Tables[0].Rows[0][1].ToString();

                    g_obj.gMain = new frmMain(userRealName);
                    this.Hide();
                    g_obj.gMain.Show();
                }
                else
                {
                    Msg.WarningBox("Invalid Credentials",
                        "You have entered an incorrect username or password.");
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error whilst talking to the database.\n" + ex.Message,
                    "Database Communication Error",
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Error);
            }

Singleton Class

CodeKeep C# Feed Aprile 3rd, 2008

Description: Example code of a singleton class

Link: http://www.codekeep.net/snippets/22b80334-6133-46b7-aa0f-dda070d4a7ac.aspx

#region Singleton
        private static ContactListData instance;
        private static int numOfReference;

        private ContactListData()
        {
            numOfReference = 0;
        }
        public static ContactListData GetInstance()
        {
            if (instance == null)
            {
                instance = new ContactListData();
            }
            numOfReference++;
            return instance;
        }
        public static int Reference
        {
            get { return numOfReference; }
        }
        #endregion

Determine is internet connection is available

CodeKeep C# Feed Aprile 3rd, 2008

Description: Determine is internet connection is available

Link: http://www.codekeep.net/snippets/5589365f-dcc4-41b6-9df9-88c6a5aa4d33.aspx

public static bool IsConnectionAvailable(string url)
{
	System.Net.WebRequest objWebReq = System.Net.WebRequest.Create(url);
	System.Net.WebResponse objResp;
	try
	{
		objResp = objWebReq.GetResponse();
		objResp.Close();
		objWebReq = null;
		return true;
	}
	catch (Exception ex)
	{
		objResp = null;
		objWebReq = null;
		return false;
	}
}

Read file and convert into byte array

CodeKeep C# Feed Aprile 3rd, 2008

Description: Read file and convert into byte array

Link: http://www.codekeep.net/snippets/2e48a9c8-51aa-47c5-a45c-4aad3d70ec56.aspx

private byte[] StreamFile(string filename)
        {
            FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);

            // Create a byte array of file stream length
            byte[] fileData = new byte[fileStream.Length];

            //Read block of bytes from stream into the byte array
            fileStream.Read(fileData, 0, System.Convert.ToInt32(fileStream.Length));

            //Close the File Stream
            fileStream.Close();

            return fileData; //return the byte data
        }

Home

maurodx Aprile 3rd, 2008

Welcome to ForexSignals!

Here you can find some useful info about my software to send forex calls to users that subscribe to your personal service!

Custom Paging in Datalist

CodeKeep C# Feed Aprile 3rd, 2008

Description: Custom Paging in Datalist

Link: http://www.codekeep.net/snippets/2dda37ee-5bb0-42ae-84e1-1f23a14e9025.aspx

public partial class DetailedProfile : System.Web.UI.Page
    {
        Int32 UGender = 0;
        Int32 FromAge = 0;
        Int32 ToAge = 0;
        Int32 Country = 0;
        Int32 Region = 0;
        Int32 HasPhoto = 0;
        Int32 IsOnline = 0;

        const int RecordPerPage = 4;
        int TotalRecords = 0;
        int Page_Number = 0;
        int TotalPages = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            UGender = Object.Equals(Request.QueryString["G"], null) ? 0 : Convert.ToInt32(Request.QueryString["G"]);
            FromAge = Object.Equals(Request.QueryString["F"], null) ? 0 : Convert.ToInt32(Request.QueryString["F"]);
            ToAge = Object.Equals(Request.QueryString["T"], null) ? 0 : Convert.ToInt32(Request.QueryString["T"]);
            Country = Object.Equals(Request.QueryString["C"], null) ? 0 : Convert.ToInt32(Request.QueryString["C"]);
            Region = Object.Equals(Request.QueryString["R"], null) ? 0 : Convert.ToInt32(Request.QueryString["R"]);
            HasPhoto = Object.Equals(Request.QueryString["HP"], null) ? 0 : Convert.ToInt32(Request.QueryString["HP"]);
            IsOnline = Object.Equals(Request.QueryString["IO"], null) ? 0 : Convert.ToInt32(Request.QueryString["IO"]);
            if (!IsPostBack)
            {
                if (Request.QueryString["id"] != null)
                    PageNumber.Value = Request.QueryString["id"].ToString();
                clsSearchResult objSearch = new clsSearchResult();
                TotalRecords = objSearch.getCount(UGender, FromAge, ToAge, Country, Region, HasPhoto, IsOnline);
                Double total = Convert.ToDouble(TotalRecords) / RecordPerPage;
                Pages.Value = Convert.ToString(Math.Ceiling(total));
                bindSearchResult();
            }           

        }

        void bindSearchResult()
        {
            Page_Number = Convert.ToInt32(PageNumber.Value);
            TotalPages = Convert.ToInt32(Pages.Value);
            DataTable dt = (new clsSearchResult()).SelectQuickResult(UGender, FromAge, ToAge, Country, Region, HasPhoto, IsOnline, Page_Number, RecordPerPage);
            searchList.DataSource = dt;
            searchList.DataBind();
            //if (TotalPages <= 0)
            //    lblError.Visible = true;
            //else
            //    lblError.Visible = false;

            PagesDisplay.Text = "";
            for (int i = 1; i <= TotalPages; i++)
            {
                if (i != Page_Number)

                    PagesDisplay.Text += "<a href='" + string.Format("DetailedProfile.aspx?id={0}&G={1}&F={2}&T={3}&C={4}&R={5}&HP={6}&IO={7}", i, UGender, FromAge, ToAge, Country, Region, HasPhoto, IsOnline) + "'>" + i + "</a>";
                else
                    PagesDisplay.Text += "[" + i + "]";

            }
            FirstPage.Enabled = (Page_Number != 1);
            PrePage.Enabled = (Page_Number != 1);
            NextPage.Enabled = (Page_Number != TotalPages);
            LastPage.Enabled = (Page_Number != TotalPages);
        }

        protected void lstDetail_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int UID = Convert.ToInt32(searchList.DataKeys[e.Item.ItemIndex]);
                //int UID = 12;
                Label lbMatch = e.Item.FindControl("lblMatch") as Label;
                lbMatch.Text = FromAge + "-" + ToAge + " Year";

                Image imUserPhoto = e.Item.FindControl("imUserPhoto") as Image;
                string str = DataBinder.Eval(e.Item.DataItem, "URL").ToString();
                if (!string.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "URL").ToString()))
                {
                    clsPhoto objPath = new clsPhoto();
                    objPath.Path = DataBinder.Eval(e.Item.DataItem, "URL").ToString();

                    imUserPhoto.ImageUrl = "../Thumbnail.ashx?ImageName=" + objPath.Path + "&Type=11&UID=" + UID + "&shadow=false";
                    //imUserPhoto.ImageUrl = DataBinder.Eval(e.Item.DataItem, "PATH").ToString();
                }
                Image imgStatus = e.Item.FindControl("imgStatus") as Image;
                Label lbStatus = e.Item.FindControl("lbStatus") as Label;
                if (IsOnline == 0)
                {
                    imgStatus.AlternateText = "Offline";
                    imgStatus.ImageUrl = "Include/images/OfflineSign.gif";
                    lbStatus.Text="Offline";

                }
                else
                {
                    imgStatus.AlternateText = "Online";
                    imgStatus.ImageUrl = "Include/images/OnlineSign.gif";
                    lbStatus.Text="Online";

                }

            }
        }

        protected void lstDetail_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "ViewProfile")
            {
                int UID = (int)searchList.DataKeys[e.Item.ItemIndex];
                Response.Redirect("UserProfile.aspx?viewUID=" + UID);
            }

            if (e.CommandName == "Email")
            {
                int UID = (int)searchList.DataKeys[e.Item.ItemIndex];
                Response.Redirect("MyMail.aspx?tabid=3&viewUID=" + UID);
            }

            if (e.CommandName == "Favourite")
            {
                int UID = (int)searchList.DataKeys[e.Item.ItemIndex];
                if (Session["UID"] != null)
                {
                    Int32 i = (new clsSend()).AddToFavourite(Convert.ToInt32(Session["UID"]), UID);
                    if (i == 1)
                        lblMsg.Text = "User added as Favourite. "; //+Convert.ToInt32(Request.QueryString["viewUID"]);
                    else if (i == 2)
                        lblMsg.Text = "User already added as Favourite.";
                    else
                        lblMsg.Text = "Error adding Favourite.";
                }
            }

            if (e.CommandName == "Flower")
            {
                int UID = (int)searchList.DataKeys[e.Item.ItemIndex];
                if (Session["UID"] != null)
                {
                    Int32 i = (new clsSend()).SendFlower(Convert.ToInt32(Session["UID"]), UID);
                    if (i == 1)
                        lblMsg.Text = "Flower has been sent."; //+Convert.ToInt32(Request.QueryString["viewUID"]);
                    else
                        lblMsg.Text = "Error sending flower.";
                }
            }
        }

        protected void PageChange_Command(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "FirstPage":
                    PageNumber.Value = "1";
                    break;
                case "PrePage":
                    PageNumber.Value = Convert.ToString((Convert.ToInt32(PageNumber.Value) - 1));
                    break;
                case "NextPage":
                    PageNumber.Value = Convert.ToString((Convert.ToInt32(PageNumber.Value) + 1));
                    break;
                case "LastPage":
                    PageNumber.Value = Pages.Value;
                    break;
            }
            bindSearchResult();
        }

        protected void lnkMiniProfile_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("SearchResult.aspx?G={0}&F={1}&T={2}&C={3}&R={4}&HP={5}&IO={6}", UGender, FromAge, ToAge, Country, Region, HasPhoto, IsOnline));
        }
    }
-----------------------------------------------------------------------
HTML PAGE
<div>

      <input id="Pages" type="hidden" value="0" runat="server" />
      <input id="PageNumber" type="hidden" value="1" runat="server"/>
      <asp:LinkButton ID="FirstPage" runat="server" CommandName="FirstPage" OnCommand="PageChange_Command">First</asp:LinkButton>
      <asp:LinkButton ID="PrePage" runat="server" CommandName="PrePage"  OnCommand="PageChange_Command">Prev</asp:LinkButton>
      <asp:Label ID="PagesDisplay" runat="server"></asp:Label>
      <asp:LinkButton ID="NextPage" runat="server" CommandName="NextPage" OnCommand="PageChange_Command">Next</asp:LinkButton>
      <asp:LinkButton ID="LastPage" runat="server" CommandName="LastPage" OnCommand="PageChange_Command">Last</asp:LinkButton>
 </div>

Stored Procedure For Paging
-----------------------------------------------------------
CREATE procedure sp_tempImage
(
@PageNumber int,
@PageSize int
)
as    

create table #tempResult
(
 id int identity Primary key,
 UID int,
 UserName varchar(50),
 Name varchar(50),
 Gender int,
 DOB datetime,
 Age int,
 Country varchar(50),
 Region varchar(50),
 EmailAddress varchar(50),
 PATH  varchar(50)
)
insert into #tempResult
select UID,UserName,Name,Gender,DOB,Age,Country,Region,EmailAddress,PATH from tempImage  

declare @fromid int
declare @toid int
set @fromid=(@PageNumber-1)*@PageSize
set @toid=@PageNumber*@PageSize
select * from #tempResult where id>@fromid and id<=@toid
  

Creating a single instance WinForm application per user.

CodeKeep C# Feed Aprile 3rd, 2008

Description: Here is a (partial) example on how to create a single instance WinForm. The stuff you need to write (very little) is explained in the usage section.

Link: http://www.codekeep.net/snippets/a8373f43-1f15-41f9-9240-3104a3179f34.aspx

using System;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace SingleInstanceWinFormApplication
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{

			bool firstApplicationInstance;

			string mutexName = Application.UserAppDataPath.Replace("\\", "+") + Assembly.GetEntryAssembly().FullName;

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			using (Mutex mutex = new Mutex(false, mutexName, out firstApplicationInstance))
			{

				if (!firstApplicationInstance)
				{
					Application.Run(new frmAlreadyRunning());
				}
				else
				{
					Application.Run(new frmMain());
				}

			}

		}

	}

}

ExecutiveNonQuerry

CodeKeep C# Feed Aprile 3rd, 2008

Description: Connect anc executive query string SQL Server

Link: http://www.codekeep.net/snippets/30fcc2a3-880e-44b7-adae-a41d09809824.aspx

   public void ExecuteNonQuery(string pcname,string DBName, string userid, string pass, string querry)
    {
        SqlConnection conn= new SqlConnection("server = "+pcname+"; database =" + DBName + ";user =" + userid + ";password =" + pass);
        conn.Open();
        SqlCommand cmd = new SqlCommand(querry);
        cmd.ExecuteNonQuery();
        conn.Close();
    }