Thursday, December 23, 2010

How to disable the ajax calender dates which are less than the current day?

 Hi All,
            I got so much help form the link bellow to solve some of issue which i need to implement on one of my project. That's why i thought to share with you so can you also get some help from here...

Disable the dates which are less than the current day

ASP.NET AJAX Calendar Extender

 This link helps me lot whenever i need some help regarding ajax calendar i just love to go there, may this will help you too .
ASP.NET AJAX Calendar Extender – Tips and Tricks

Thursday, November 18, 2010

Connection string properties

 For any kind of database connection issues i prefer to have a look here, i am damn sure this will help you. :)
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx

Friday, November 12, 2010

Sql Query For Returning Hierarchical Data

When we need such type of return from a stored procedure which has a parent child relationship and a level (To bind a treeview or a dropdownlist) we need to know about CTE  its help us to do the same. So here I'm showing you how could we iplemet this as per our requirement.

 Recursive Queries Using Common Table Expressions(CTE)

-- Create an Employee table.
CREATE TABLE dbo.MyEmployees
(
 EmployeeID smallint NOT NULL,
 FirstName nvarchar(30)  NOT NULL,
 LastName  nvarchar(40) NOT NULL,
 Title nvarchar(50) NOT NULL,
 DeptID smallint NOT NULL,
 ManagerID int NULL,
 CONSTRAINT PK_EmployeeID 
PRIMARY KEY CLUSTERED (EmployeeID ASC) 
);
-- Populate the table with values.
INSERT INTO dbo.MyEmployees VALUES 
 (1, N'Ken', N'Sánchez', 
N'Chief Executive Officer',16,NULL)
,(273, N'Brian', N'Welcker', 
N'Vice President of Sales',3,1)
,(274, N'Stephen', N'Jiang', 
N'North American Sales Manager',3,273)
,(275, N'Michael', N'Blythe', 
N'Sales Representative',3,274)
,(276, N'Linda', N'Mitchell', 
N'Sales Representative',3,274)
,(285, N'Syed', N'Abbas', 
N'Pacific Sales Manager',3,273)
,(286, N'Lynn', N'Tsoflias', 
N'Sales Representative',3,285)
,(16,  N'David',N'Bradley',
N'Marketing Manager', 4, 273)
,(23,  N'Mary', N'Gibson', 
N'Marketing Specialist', 4, 16);

 -----------------------------------------------------------------------------
CREATE proc [dbo].[sp_ReturningHierarchicalData]
AS
--Recursive Queries Using Common Table Expressions
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(
-- Anchor member definition
    SELECT
        e.ManagerID ,
        e.EmployeeID,
        e.Title,
        e.DeptID,
        0 AS Level
    FROM
        MyEmployees AS e
    WHERE
        e.ManagerID IS NULL
    UNION ALL
-- Recursive member definition
    SELECT
        e.ManagerID,
        e.EmployeeID,
        e.Title,
        e.DeptID,
        Level + 1
    FROM
        MyEmployees AS e
    INNER JOIN
        DirectReports AS d
    ON e.ManagerID = d.EmployeeID
)
-- Statement that executes the CTE
SELECT
    ManagerID,
    EmployeeID,
    --Case
    --    When Level = 0 Then  Title ----level 0
    --    When Level = 1 Then  convert(nvarchar(50),'  ' + Title)----level 1
    --    When Level = 2 Then  convert(nvarchar(50),'    ' + Title)----level 2
    --                    Else convert(nvarchar(50),'      ' + Title)----level 3
    --End as Title,
    Title,
    DeptID,
    Level
FROM DirectReports
-------------------
 Result
------------------------------------------------------------------------------------------
ManagerID   EmployeeID    Title                                  DeptID      Level
----------- ---------- ----------------------------- --------------------------------------
NULL        1                      Chief Executive Officer               16              0
1                273                  Vice President of Sales               3               1
273            16                    Marketing Manager                      4                2
273            274                  North American Sales Manager  3                2
273            285                  Pacific Sales Manager                3                2
285            286                  Sales Representative                  3                3
274            275                  Sales Representative                  3                3
274            276                  Sales Representative                  3                3
16              23                    Marketing Specialist                    4                3
--------------------------------------------------------------------------------------------
More details : http://msdn.microsoft.com/en-us/library/ms186243.aspx

 Hope this helps you , i got this from the link above as an query and i implement this as stored procedure.

Monday, October 11, 2010

How to rename folder in c#?

Here I'm showing how to rename a folder or Directory in C#. Before going to the code we need some dll to add in our project. So we have to add reference to Microsoft.VisualBasic.dll
 
Here the code to rename the folder

using Microsoft.VisualBasic.MyServices; 


 try
        {
            FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
            // FileSystem.RenameDirectory("original folder path", "new name");
            FileSystem.RenameDirectory(Server.MapPath("~/bishnu"), "Bishnu1"); //this will rename bishnu to Bishnu1
            FileSystem = null;
        }
        catch (Exception ex) { } 

Thursday, September 30, 2010

How to disable text selection of any asp.net control?

To disable text selection of any asp.net control just put this  style within the head tag

  <style type="text/css">
body
        {
            -moz-user-select: none;
        }
</style>

How to disable browser back button in asp.net with javascript?

Here i am showing how to disable browser back button . Just put this java script on the aspx page within the head section. Here i put this on my master page
 <script type = "text/javascript" >
             function disableBrowserBackButton() {
                 window.history.forward();
             }
             setTimeout("disableBrowserBackButton()", 0);
</script> 

On the Body tage put this onload="disableBrowserBackButton()"
e.g
<%@ Master Language="VB" AutoEventWireup="false" CodeBehind="Main.master.vb" Inherits="talklouds.Main" %>
<%@ Register src="UserControl/MainHeader.ascx" tagname="MainHeader" tagprefix="uc1" %>
<%@ Register src="UserControl/Mainfooter.ascx" tagname="Mainfooter" tagprefix="uc2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>talkloud.de</title>
         <script type = "text/javascript" >
             function disableBrowserBackButton() {
                 window.history.forward();
             }
             setTimeout("disableBrowserBackButton()", 0);
</script> 
        <style type="text/css" media="screen">
              @import url(css/style.css);
              @import url("css/bishnu.css");
        </style>
    <script language="javascript" type="text/javascript" src="JS/jquery-1.3.2.min.js"></script>
    <script language="javascript" type="text/javascript" src="JS/jquery-ui-1.7.2.custom.min.js"></script>
    <script type="text/javascript" language ="javascript" src ="js/Validations.js"></script>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body onload="disableBrowserBackButton()">
     <form id="form1" runat="server">
     <div id="wrapper">

 </div>    
    </form>
</body>
</html>

Thursday, July 22, 2010

How to disable copy paste and cut on textbox in asp.net?


1. Simple prevent copy paste or cut on a textbox
------------------------------------------------
<asp:TextBox ID="txtPrevent" runat="server"
        oncopy="return false"
        onpaste="return false"
        oncut="return false">
</asp:TextBox>
------------------------------------------
2. Prevent right click on the textbox
----------------------------------------
javascript:
function preventRightClick(event)
{
if (event.button==2)
{
alert("Right Clicking disabled!");
}
}
<asp:TextBox ID="txtRightClickOff" runat="server"
onMouseDown="preventRightClick(event)">
</asp:TextBox>
--------------------------
3. Prevent ctrl key
---------------------------
javascript:
function PreventCtrlKey(e)
{
var code = (document.all) ? event.keyCode:e.which;
if (parseInt(code)==17)
{
alert('Ctrl key disabled');
window.event.returnValue = false;
}
}
<asp:TextBox ID="txtCtrl" runat="server"
onKeyDown="return PreventCtrlKey(event)">
</asp:TextBox>

Saturday, June 26, 2010

Trigger in Sql Server

Here is the sample of how to write trigger in sql server . The first one(InsertIntoPlayerProfile) will fire when record inserted into the  tbl_Player it will automatically insert the PlayerId into the tbl_PlayerProfile where table inserted is the temp table created when any table of the database is modified due to insert or update query.deleted is also the temp table created when any record deleted from the table.


CREATE  TRIGGER [dbo].[InsertIntoPlayerProfile]
ON [dbo].[tbl_Player]
AFTER INSERT
AS
Insert Into tbl_PlayerProfile(PlayerId)
SELECT i.PlayerId
FROM inserted AS i

Now for the Update 

CREATE TRIGGER [dbo].[UpdateIntoLogin]
ON [dbo].[tbl_Player]
AFTER Update
AS
   Update tbl_Login
Set Email=(SELECT i.Email
    FROM inserted AS i)
Where
UserName=(SELECT i.UserName
    FROM inserted AS i)


Now for Delete

CREATE TRIGGER [dbo].[DeleteFromPlayerProfile]
ON [dbo].[tbl_Player]
AFTER Delete
AS
--Delete Record from the tbl_PlayerProfile table for the related PlayerId
Delete from tbl_PlayerProfile
WHERE EXISTS
(
    SELECT d.PlayerId
    FROM deleted AS d
    WHERE tbl_PlayerProfile.PlayerId=d.PlayerId
)
 

Wednesday, June 23, 2010

Return Type Stored Procedure in SQL

We can get a return from a stored procedure from another stored procedure , here sp_GetEmpTypeId  is use to return EmpTypeId From tbl_EmpType for an EmpType and sp_CreateEmployee which is calling  sp_GetEmpTypeId will insert empname  and the returned typeId into the EmpDetails table for a EmpName
-----------------------------------------------
Create procedure sp_GetEmpTypeId
(
    @EmpType nvarchar(150),
    @EmpTypeId int=0 output
)
As
If  @EmpType is not Null
Begin
    If Not Exists(Select EmpType From tbl_EmpType where EmpType=@EmpType)
        Begin
            Insert Into tbl_EmpType Values(@EmpType)
            Select @EmpTypeId=@@IDENTITY
        End
    Else
        Begin
            Select @EmpTypeId=(Select EmpTypeId From tbl_EmpType where EmpType=@EmpType)
    End
End

----------------
create proc sp_CreateEmployee
(
    @empname nvarchar(50),
    @EmpType  nvarchar(50)
)
As
Declare @typeId int
Set @typeId=0
---This will return the @typeId for the @EmpType
Exec sp_GetEmpTypeId @EmpType, @typeId output
----
Insert into EmpDetails
        (
            empname,
            typeId
        )
        values
        (
            @empname,
            @typeId
        )
       
      

Friday, April 2, 2010

How to filter file extension and get file size in C# ?

 Here form this function I'm trying to filter extension and size for uploading  a file in asp.net
public static string FilteredFileExtension(HttpPostedFile httpPostedFile)
    {
        int intFileLength = httpPostedFile.ContentLength;   // File size
        string strExtn = System.IO.Path.GetExtension(httpPostedFile.FileName.ToLower()); //File extension
        if (intFileLength < 4096000)// 4mb
        {
            if (strExtn == ".jpg" || strExtn == ".gif" || strExtn == ".png")
            {
                return string.Empty;  // only jpg,gif and png files and less dn 4mb can be uploaded
            }
            else
            {
                return strExtn + " File not accepted";
            }
        }
        else
        {
            return "File is very large";
        }
    }

Wednesday, March 17, 2010

How to find control on GridView RowCommand Event?

Here I'm showing how to find a control within a gridview to get some data of that control.
<Columns>
 <asp:TemplateField HeaderText="Team">
    <ItemTemplate>
     <asp:Label ID="lblTeam" runat="server" Text='<%# Eval("TeamName")%>'></asp:Label>
   </ItemTemplate>
 </asp:TemplateField>
</Columns>
<Columns>
 <asp:TemplateField>
    <ItemTemplate>
       <asp:LinkButton ID="lnkEdit" Text="EDIT" runat="server" CssClass="coachEdit"   CommandArgument='<%# Eval("TeamId")%>' CommandName="Redirect"></asp:LinkButton>
   </ItemTemplate>
 </asp:TemplateField>
</Columns>

Here i need the Team Name from the lblTeam and I'm like to get this when I click the Edit link means lnkEdit  so on RowCommand event i have to write this code


GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
 Label lblDate = (Label)row.Cells[0].FindControl("lblDate");
string teamName= lblDate.Text;
int rowindex = row.RowIndex;

Friday, February 26, 2010

Tuesday, February 23, 2010

How to upload and resizing image in asp.net?

Here is the code:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (flUpImage.HasFile)
        {
            picName = flUpImage.FileName;
            string SavePath = Server.MapPath("~/Coach/Data/" + Convert.ToString(iPlayConstant._PLAYER_ID) + "/");
            DirectoryInfo di = new DirectoryInfo(SavePath);
            if (!di.Exists)
            {
                di.Create();
                SetPermissions(SavePath);
            }
            string LocalPath = Server.MapPath("~/Coach/Data/" + Convert.ToString(iPlayConstant._PLAYER_ID) + "/Profile.gif");
            flUpImage.SaveAs(LocalPath);
            System.Drawing.Image imgSaved = System.Drawing.Image.FromFile(LocalPath);
            System.Drawing.Image imgCroped;
            imgCroped = ImageResize(imgSaved, 250, 250);//pass the height and width value to create thumbnail picture
            imgProfile.Width = imgCroped.Width;
            imgProfile.Height = imgCroped.Height;
            imgSaved.Dispose();
            imgCroped.Save(LocalPath);
            imgCroped.Dispose();
            imgProfile.Src = "~/Coach/Data/" + Convert.ToString(iPlayConstant._PLAYER_ID) + "/Profile.gif";
        }
    }


    protected static System.Drawing.Image ImageResize(
        System.Drawing.Image imgPhoto, int dWidth, int dHeight)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int destWidth = dWidth;
        int destHeight = dHeight;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;
        float percent = 0;

        if (sourceHeight > sourceWidth)
        {
            percent = (float)sourceWidth / (float)sourceHeight;
            destWidth = (int)(percent * destWidth);
        }
        else
        {
            percent = (float)sourceHeight / (float)sourceWidth;
            destHeight = (int)(percent * destHeight);
        }
        if (destWidth > destHeight)
        {
            percent = (float)sourceHeight / (float)sourceWidth;
            destWidth = (int)(percent * destWidth);
        }
        System.Drawing.Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, destWidth, destHeight),
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
        GraphicsUnit.Pixel);
        grPhoto.Dispose();
        return bmPhoto;
    }

How to use Ajax AutoCompleteExtender in Asp.net Project

Here is an example how to use Ajax AutoCompleteExtender control in asp.net project, to use Ajax AutoCompleteExtender you have to have some knowledge of web services and javascript and little bit of jquerie. The basic concept on Ajax AutoCompleteExtender you can fine in the Ajax help side here i have add one extra properties on it . Here I have fill the control like a asp dropdownlist where we have textvaluefield and datavaluefield. So you can get the value fileld of a particular selected list item.
Step 1: Add a textbox  ID=txtOppTeam and runat="server"  AutoComplete="off"
2:JavaScript
function OppTeams_itemSelected(sender, e)
    {
        var hdOpponentTeamId = $get('<%= hdOpponentTeamId.ClientID %>');
        var hdCreateNewTeam = $get('<%= hdCreateNewTeam.ClientID %>');
        hdOpponentTeamId.value = e.get_value();
        //alert('selected id=' + hdOpponentTeamId.value);
        if(hdOpponentTeamId.value>0)
        {
            hdCreateNewTeam.value=1;
        }
        else
        {
            hdCreateNewTeam.value=0;
        }
    }





3:Web Service Class: add an webservice as AutoCompleteTeam

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
///
/// Summary description for AutoCompleteTeam
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 [System.Web.Script.Services.ScriptService]
public class AutoCompleteTeam : System.Web.Services.WebService {

    public AutoCompleteTeam () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        iPlayTeam dsTeam = new iPlayTeam();
        dsTeam.TeamName = Convert.ToString(prefixText);
        Collection allTeam = iPlayBL.GetTeamNameAs(dsTeam);
        List items = new List(0);
        if (allTeam.Count > 0)
        {
            items = new List(allTeam.Count);
            for (int i = 0; i < allTeam.Count; i++)
            {
                items.Add(allTeam[i].TeamName);
            }
        }
        return items.ToArray();
       
    }
    [WebMethod]
    public string[] GetOpponentTeamList(string prefixText, int count)
    {
        iPlayTeam dsTeam = new iPlayTeam();
      
        dsTeam.TeamName = Convert.ToString(prefixText);
        //dsTeam.PlayerId = Convert.ToInt64(Session["playerId"]);
        dsTeam.PlayerId = iPlayConstant._PLAYER_ID;
        //dsTeam.SportId = Convert.ToInt64(Session["SportId"]);
        dsTeam.SportId = iPlayConstant._SPORT_ID;
        Collection allTeam = iPlayBL.GetOppnentTeamNameAs(dsTeam);
        List retItems = new List(0);
        if (allTeam.Count > 0)
        {
            retItems = new List(allTeam.Count);
            for (int i = 0; i < allTeam.Count; i++)
            {
                retItems.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(allTeam[i].TeamName, Convert.ToString(allTeam[i].TeamId)));
            }
        }
        return retItems.ToArray();
       
    }
}

4.Ajax Autocomplete extender :




Thursday, January 7, 2010

How to enable task manager ?

If your task manager is disable by some viruses and you are not able to resolve it then do the following thing , hope it will helps you

Start--->Run ---->
REG add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System /v DisableTaskMgr /t REG_DWORD /d 0 /f