Wednesday, September 11, 2013

webservice to insert multiple data from custom xml

  [WebMethod]

    public XmlDocument SaveDataMethod(string xml)

    {

        try

        {

            objExceptionLog.LogMessage("Confirm if method called", "SaveDataMethod");

            int UserID = 0;

            DateTime VisitDate = DateTime.Now;

            int DealerID = 0;

            string Remarks = "";

            decimal Collection = 0;

            string ChequeDDNo = "";

            DateTime ChequeDDDate = DateTime.Now;

            DataSet ds = new DataSet();

            ds = Decode(xml);

            foreach (DataRow dr in ds.Tables[0].Rows)

            {

                UserID = Convert.ToInt32(dr["UserID"]);

                VisitDate = Convert.ToDateTime(dr["VisitDate"]);

                DealerID = Convert.ToInt32(dr["DealerID"]);

                Remarks = Convert.ToString(dr["Remarks"]);

                Collection = Convert.ToDecimal(dr["Collection"]);

                ChequeDDNo = Convert.ToString(dr["ChequeDDNo"]);

                ChequeDDDate = Convert.ToDateTime(dr["ChequeDDDate"]);

                string strresult = "";

                BusinessDealerVisit objBusiness = new BusinessDealerVisit();

                strresult = objBusiness.Save(new EntityDealerVisit

                {

                    DealerVisitUserID = UserID,

                    Date = VisitDate,

                    VisitedDealerID = DealerID,

                    Remarks = Remarks,

                    Collection = Collection,

                    ChequeDDNo = ChequeDDNo,

                    ChequeDDDate = ChequeDDDate

                });

                //Console.WriteLine(dr["ColName"].ToString());

            }

            //List<string> MyCollection = new List<string>();

            //XElement xmlTree = XElement.Parse(xml);

            //foreach (XElement e1 in xmlTree.Elements())

            //{

            //    string values = e1.Value;

            //    MyCollection.Add(values);

            //}

            //MyCollection.ToArray();

            //UserID = Convert.ToInt32(MyCollection[0]);

            //VisitDate = Convert.ToDateTime(MyCollection[1]);

            //DealerID = Convert.ToInt32(MyCollection[2]);

            //Remarks = Convert.ToString(MyCollection[3]);

            //Collection = Convert.ToDecimal(MyCollection[4]);

            //ChequeDDNo = Convert.ToString(MyCollection[5]);

            //ChequeDDDate = Convert.ToDateTime(MyCollection[6]);

            //string strresult = "";

            //BusinessData objBusiness = new BusinessData ();

            try

            {

                //    strresult = objBusiness.Save(new EntityData

                //    {

                //        DealerVisitUserID = UserID,

                //        Date = VisitDate,

                //        VisitedDealerID = DealerID,

                //        Remarks = Remarks,

                //        Collection = Collection,

                //        ChequeDDNo = ChequeDDNo,

                //        ChequeDDDate = ChequeDDDate

                //    });

                Document = CreateBaseStringBuilder();

                Document.AppendLine("<SaveData>");

                Document.AppendLine("<Message>" + "Data Saved sucessfully" + "</Message>");

                Document.AppendLine("</SaveData>");

                XMLDocument.LoadXml(Document.ToString());

                objExceptionLog.LogMessage("Confirmation SaveData Saved sucessfully", "InsertDealerVisit");

                return (XMLDocument);

                //}

            }

            catch (Exception ex)

            {

                Document = CreateBaseStringBuilder();

                Document.AppendLine("<SaveData>");

                Document.AppendLine("<Message>" + "Error Saving Record" + "</Message>");

                Document.AppendLine("</SaveData>");

                XMLDocument.LoadXml(Document.ToString());

                objExceptionLog.LogMessage("Error Saving Record", "SaveDataMethod");

                return (XMLDocument);

            }

        }

        catch (Exception ex)

        {

            objExceptionLog.LogErrorMessage(ex, "SaveDataMethod");

            return null;

        }

    }


  public DataSet Decode(string xml)
    {
        try
        {
            StringReader theReader = new StringReader(xml);
            DataSet theDataSet = new DataSet();
            theDataSet.ReadXml(theReader);

            return theDataSet;
        }
        catch (Exception ex)
        {
            objExceptionLog.LogErrorMessage(ex, "Decode");
            return null;
        }
    }

Monday, August 19, 2013

Create webservice to get custom xml structure

* Add below line of code to your service.cs , used three tier architecture and Commented out direct db call .


#region HeaderOfXml
    private StringBuilder CreateBaseStringBuilder()
    {
        StringBuilder BaseDocument = new StringBuilder();
        BaseDocument.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        return (BaseDocument);
    }
    #endregion



    [WebMethod]
    public XmlDocument GetDealerList()
     {
         //  DataSet ds = new DataSet();
          //  SqlConnection cnn = new //SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ConnectionString);
    //    cnn.Open();
    //         SqlCommand mycommand = new SqlCommand("usp_testSp", cnn);
 //       mycommand.CommandType = CommandType.StoredProcedure;
  //      SqlDataAdapter adp = new SqlDataAdapter(mycommand);
  //      adp.Fill(ds);


        BusinessDealerList objBusiness = new BusinessDealerList();
        DataSet ds = objBusiness.GetDealerList();
        // ds = DealerCollection;
        EntityDealerList ObjEntity = new EntityDealerList();

        //DataSet ds1 = new DataSet();
        Document = CreateBaseStringBuilder();
        Document.AppendLine("<Dealer>");

//use for each to loop through each data
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            ObjEntity.Code = dr["Code"].ToString();
            ObjEntity.Name = dr["Name"].ToString();
            Document.AppendLine("<Dealer>");
            Document.AppendLine("<Code>" + ObjEntity.Code + "</Code>");
            Document.AppendLine("<Name>" + ObjEntity.Name + "</Name>");
            Document.AppendLine("</Dealer>");

        }
        Document.AppendLine("</Dealer>");
        XMLDocument.LoadXml(Document.ToString());


// Add this if you want to create an xml and write data in it
        // Save the document to a file 

        XmlTextWriter writer = new XmlTextWriter(@"C:\data.xml", null);
        writer.Formatting = Formatting.Indented;
        XMLDocument.Save(writer);

        return (XMLDocument);

    }


//inside webconfig add below 
 <connectionStrings>
    <remove name="LocalSqlServer" />

    <add name="
Connect" connectionString="data source=10.11.48.89;uid=sa;pwd=abcd;initial catalog=testDB" providerName="system.data.sqlclient"/>
   
  </connectionStrings>



Monday, August 12, 2013

The benefits of normalization


The two main benefits you get from normalization.
Benefit #1: Reduce data redundancy.
Unless absolutely necessary, storing redundant data is a waste of system resources. Nowadays hard disk space is cheap but is not free. More importantly, maintaining very large size of databases requires more work on database administrators and network engineers.
Benefit #2: Reduce data inconsistency.
The data redundancy issue can further cause date inconsistency issues. As we keep the same piece of data across different locations, we have to make sure that they are kept exactly the same all the time. For example, when one piece of data is updated, the same data in other locations has to be updated as well.
The issues of data inconsistency are collectively called Data Anomaly. There are four types of possible errors they could cause. These four types of errors are the causes of data anomaly:
Select anomaly (also known as join anomalies):
This happens when we select the same piece of data from different tables but they could produce different results.
Update anomalies
This occurs when we update the same piece of data in more than one place. If care not taken, we could end up with updating the data in one place but forgot to update it in another place.
Insertion anomalies
This can happen when we are adding a new record for the data. If we forgot to insert it to other places for the same data, data inconsistency occurs.
Deletion anomalies
This happens when we delete data. If the deletion does not remove the same data from all places, data anomalies occur.

ASP.NET MVC Execution Process







Introduction to MVC Architecture


MVC is an architectural pattern that splits interactions between users and applications into three roles:
* Model (business logic)
* View (user interface)
* Controller (user input) 
Model 
                 The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). 
      View
The view manages the display of information.
        Controller
The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate. 
 
o Controller contains all Controller classes.
o Models contains all Models classes.
o Views contains associated views.
o Content contains all CSS / Images / other libraries
o Script contains default scripts loaded MVC
 
 
 
 
 
 
 
 

Tuesday, July 16, 2013

Checkbox selection check and loop through the checkboxlist ,asp.net /c#

 //.aspx code

 <asp:CheckBoxList runat="server"  RepeatColumns="0" Height="250" Width="150"  RepeatDirection="Vertical"
                                                   CssClass="btext" ID="chkLstSkill">
                                               </asp:CheckBoxList>

//.cs code
 string values = "";
if (chkLstSkill.SelectedValue = = "")
                {
       //do something if not selected          
}
else
{

  // We perform a for loop to check if each checkbox is selected then we get the value
                    foreach (ListItem objItem in chkLstSkill.Items)
                    {
                        if (objItem.Selected)
                        {
                            values += objItem.Value;
                            TrainingID = values;
                        
             //Use below if u want only one id at a time else dont use it
              //       values = "";
                //    TrainingID = ""; //
                  
                        }

}

Steps to create Horizontal or pivoted table through rdlc report/asp.net/C# and if suppose selection is dynamic


 //I had a task where i need to display Zone,Areaname,DealerCode,DealerName,EmployeeCode,EmployeeName,Role and tricking part whatever course user selects it should only show that course and its course schedule time.
//For course selection i used Checkbox list

//Codebehind i put a condition for Checkbox selection

 if (chkLstSkill.SelectedValue == "")
                {
}
else
{
ReportViewerDealerStatus.Visible = true;                                                     //Reports Div is Enabled True
                    ReportViewerDealerStatus.Reset();
                    ReportViewerDealerStatus.ProcessingMode = ProcessingMode.Local;



                    ReportDataSource objRDS;
                    LocalReport objLRPT = new LocalReport();
                    objLRPT = ReportViewerDealerStatus.LocalReport;

                    //objLRPT.Refresh();

                    objLRPT.ReportPath = Server.MapPath("../RDLC/TrainingReadinessReport.rdlc");

                    //Set Reports Parametres                                                                                                           
                    ReportParameter[] p ={              
                               new ReportParameter("Title","Some Report")};
                    objLRPT.SetParameters(p);
                    objRDS = new ReportDataSource();

                    objRDS.Name = "DataSet1";
                    BusinessRptTrainingReadiness.Delete(new EntityRptTrainingReadiness
                    {
                        sessionid = Session.SessionID
                    });

                    // We perform a for loop to check if each checkbox is selected then we get the value
                    foreach (ListItem objItem in chkLstSkill.Items)
                    {
                        if (objItem.Selected)
                        {
                            values += objItem.Value;
                            TrainingID = values;
                        
                          //  BusinessRptTrainingReadiness obj
                    BusinessRptTrainingReadiness.Save(new EntityRptTrainingReadiness
                     {
                         TrainingID = TrainingID,
                        sessionid=Session.SessionID
                     });

                  
                    values = "";
                    TrainingID = "";
                  
                        }
                       // objLRPT.DataSources.Add(objRDS);
                        //divReport.Visible = true;
                        //ReportViewerDealerStatus.Visible = true;
                    }
                    sessionid = Session.SessionID;
                                     objRDS.Value = new BusinessRptTrainingReadiness().RptTrainingReadiness(ChannnelID, DealerID, AreaID, ZoneID, TrainingID, sessionid, Role); //Gets procedure from business logic

                    objLRPT.DataSources.Clear();
                    objLRPT.DataSources.Add(objRDS);
                    divReport.Visible = true;
                    ReportViewerDealerStatus.Visible = true;

}

//For this  first created a dummy table
Consisting of TrainingID and sessionid

on checkbox selection it first deleted all the content from the table for the sessionid and inserted user selection. and inside the procedure i call the trainingID from the table using 'in' clause example(MPT.TrainingId IN (select TrainingId from DumyTrainingReadiness where sessionid =@sessionid))







CREATE Procedure Sp_test      
@ChannelID nvarchar(100),       
@DealerID nvarchar(100),         
       
@AreaID nvarchar(100),         
       
@ZoneID nvarchar(100),        
       
@RoleID nvarchar(100),       
@TrainingID nvarchar(100),       
@sessionid nvarchar(100)       
       
as       
       
SELECT Distinct MZ.ZONE,MA.AREANAME as AO,D.Code as DealerCode,D.Name as DealerName,MP1.EmployeeCode,         
(MP1.FirstName + ' ' + MP1.LastName) as Name,MS.SkillName as empRole,MT.Code,MPT.TrainingCompletionDate              
FROM MAS_AREA MA            
INNER JOIN MAS_ZONE MZ ON MA.ZONEID=MZ.ID          
          
INNER JOIN DEALER D ON MA.ID=D.AREACODEID           
INNER JOIN DEALERLOCATION  DL ON D.ID=DL.DEALERID  and DL.IsActive=1         
INNER JOIN DEALERCHANNELMAPPING DM ON D.ID=DM.DEALERID and D.IsActive=1         
inner join ManPowerTraining MPT on DL.ID=MPT.ManPowerId and MPT.IsActive=1         
INNER JOIN LOCATIONMANPOWERASSOCIATON LMA ON LMA.MANPOWERID = MPT.MANPOWERID and  LMA.ENDDATE IS NULL           
inner join  ManPower MP1 on MP1.ID=MPT.ManPowerId and MP1.IsActive=1         
inner join  ManPowerExperience MPE1 on MP1.ID=MPE1.ManPowerId and MPE1.IsActive=1         
inner join  Mas_Skills MS on MS.ID=LMA.SkillID and MS.IsActive=1         
inner join Mas_Training MT on MT.ID=MPT.TrainingId and MT.IsActive=1        
where       
 MPT.TrainingId IN (select TrainingId from DumyTrainingReadiness where sessionid =@sessionid)  -- 23 --COTEK BAISC MODULE - PERSONAL         
 --AND MT.ISACTIVE = 1         
 and       
 (@RoleID=0 OR @RoleID=NULL OR MPE1.SKILLID =@RoleID)-- 8 --COTEK  (role)       
AND DM.CHANNELID=@ChannelID --20         
 AND (@AREAID=0 OR @AREAID=NULL OR MA.ID=@AREAID)         
 AND (@DEALERID=0 OR @DEALERID= NULL OR D.ID=@DEALERID)         
AND (@ZONEID=0 OR @ZONEID=NULL OR MZ.ID=@ZONEID)        
   --Area       
  --Dealer       
 --AND MZ.ID=@ZONEID  --Zone       
        
order BY MZ.ZONE,MA.AREANAME

//

in the rdlc design
use matrix table instead of normal table
Afterbinding it to dataset,in the properties of the matrix table select group by to some id ,in my case i used EmployeeCode.

create disk space

#include "Ifx.h"
 prototype Get_disk_Space();
function Get_disk_Space()
    STRING   szDrive,svResultPath;
    long freespace,i;
    NUMBER   nvResult;
    ///LIST     listInfo;
begin 
   freespace=0;
AskPath ("Select drive:", "C:\\", svResultPath);
   i=0;
   freespace= GetDiskSpace(szDrive);  
  
   if(freespace<i) then
  
   // MessageBox ("not enough space", SEVERE);
    //  Disable (NEXTBUTTON);
 
       endif;
       
         if(freespace>i) then
        Enable (NEXTBUTTON);
        // MessageBox ("enough space,go ahead", INFORMATION);
   
       
       endif;
        ///Enable (FINISHBUTTON);
   
      end;
  
  
  
    // Create a list for system information.
  //  listInfo = ListCreate (STRINGLIST);
    // Get the amount of extended memory.
   // if (GetSystemInfo (EXTENDEDMEMORY, nvResult, svResult) < 0) then
       // szInfo = "Couldn't get EXTENDEDMEMORY info.";
   // else
     //   Sprintf(szInfo, "Extended memory: %d K", nvResult);
 //   endif;
    // Add the information to the list.
  //  ListAddString(listInfo, szInfo, AFTER);
    // Get the boot drive.
   // if (GetSystemInfo (BOOTUPDRIVE, nvResult, svResult) < 0) then
       // szInfo = "Couldn't get BOOTUPDRIVE info.";
   // else
       // Sprintf(szInfo, "Boot drive: %s", svResult);
    //endif;
    // Add the information to the list.
  //  ListAddString(listInfo, szInfo, AFTER);
    // Get info about the CD-ROM.
   // if (GetSystemInfo (CDROM, nvResult, svResult) < 0) then
       // szInfo = "Couldn't get CD-ROM info.";
   // else
       // if (nvResult = 0) then
          //  svResult = "No";
       // else
          //  svResult = "Yes";
      //  endif;
       
       // Sprintf(szInfo, "CDROM: %s", svResult);
    //endif;
    // Add the information to the list.
   // ListAddString(listInfo, szInfo, AFTER);
    // Get the video adapter.
  //  if (GetSystemInfo (VIDEO, nvResult, svResult) < 0) then
       // szInfo = "Couldn't get VIDEO info.";
   // else
       // switch (nvResult)
          //  case IS_UNKNOWN:
            //    szInfo = "VIDEO: UNKNOWN";
          //  case IS_SVGA:
           //     szInfo = "VIDEO: SVGA";
           // case IS_XVGA:
               // szInfo = "VIDEO: XVGA";
           //// case IS_UVGA:
            //    szInfo = "VIDEO: UVGA";
       // endswitch;
   // endif;
    // Add the information to the list.
    //ListAddString(listInfo, szInfo, AFTER);
    // Get number of available colors.
    //if (GetSystemInfo (COLORS, nvResult, svResult) < 0) then
        //szInfo = "Couldn't get COLORS info.";
   // else
       // Sprintf(szInfo, "Number of colors: %d", nvResult);
    //endif;
    // Add the information to the list.
 //   ListAddString(listInfo, szInfo, AFTER);
    // Get the current date.
  //  if (GetSystemInfo (DATE, nvResult, svResult) < 0) then
  //      szInfo = "Couldn't get DATE info.";
   // else
     //   Sprintf(szInfo, "DATE: %s", svResult);
    //endif;
    // Add the information to the list.
    //ListAddString(listInfo, szInfo, AFTER);
    // Get the current time.
  //  if (GetSystemInfo (TIME, nvResult, svResult) < 0) then
      //  szInfo = "Couldn't get TIME info.";
   // else
      //  Sprintf(szInfo, "TIME: %s", svResult);
    //endif;
  //
  //  // Add the information to the list.
   // ListAddString(listInfo, szInfo, AFTER);
   // // Get the operating system.
  //  if (GetSystemInfo (OS, nvResult, svResult) < 0) then
       // szInfo = "Couldn't get Operating System info.";
    //else
        //switch (nvResult)
           // case IS_WINDOWSNT:
             //   szInfo = "OS: Windows NT";
          //  case IS_WINDOWS9X:
               // GetSystemInfo (WINMINOR, nvResult, svResult);
               
              //  if (nvResult < 10) then
                   //  szInfo = "OS: Windows 95";
              //  else
                  //   szInfo = "OS: Windows 98";
             //   endif;
      //  endswitch;
   // endif;
 //   // Add the information to the list.
//    ListAddString(listInfo, szInfo, AFTER);
//    // Display the information.
//    szTitle   = "System Information";
//    szMsg     = "The following is some information related to your system:\n";
   
  //  SdShowInfoList (szTitle, szMsg, listInfo);
 //   ListDestroy(listInfo);
//end;

Example of a procedure using IF condition and it takes multiple training ID at any given time


Create Procedure Sp_test    
           
@ChannelID nvarchar(100),           
@DealerID nvarchar(100),           
@AreaID nvarchar(100),             
@ZoneID nvarchar(100),   
@TrainingID nvarchar(100)  ,
@sessionid nvarchar(100),         
@RoleID nvarchar(100)            
as           
           
declare  @str varchar(1000)           
Begin           
set @str= 'select distinct z1.Zone,A1.AreaName as AO ,D1.ID,D1.Code as dealerCode,D1.Name as DealerName,MPE1.ManPowerId,MP1.EmployeeCode,   
(MP1.FirstName + '''' + MP1.LastName) as Name,   
(select SkillName from dbo.Mas_Skills where ID=MPE1.SkillId) as empRole,MPT.TrainingId,MT.Code,MPT.TrainingCompletionDate   
 from DealerChannelMapping DM1,Dealer D1 ,Mas_Zone Z1,Mas_Area A1,   
  dbo.ManPowerExperience MPE1,   
 ManPower MP1 ,ManPowerTraining MPT,Mas_Training MT ,Mas_Skills MS 
where D1.ID=DM1.DealerID  and Z1.ID=A1.ZoneId  and MS.ID=MPE1.SkillId   
and MPE1.DealerID=D1.ID and MPT.TrainingId=MT.ID and  MS.IsActive=1  and MPE1.IsActive=1
and D1.IsActive=1 and MT.IsActive=1 and MPT.IsActive=1 and DM1.IsActive=1 and MP1.IsActive=1
and Z1.IsActive=1 and A1.IsActive=1 and
MPE1.ManpowerId=MP1.ID '           
           
if (@ChannelID <> 0)            
begin           
set @str= @str + ' and DM1.ChannelID='+@ChannelID            
end           
           
if (@DealerID <> 0)            
begin           
set @str= @str + ' and  DM1.DealerID='+@DealerID             
end           
           
           
if (@ZoneID <> 0)            
begin           
set @str= @str + ' and  Z1.ID='+@ZoneID             
end           
           
if (@AreaID <> 0)            
begin           
set @str= @str + ' and  A1.ID='+@AreaID            
end           
 if (@RoleID <> 0)            
begin           
set @str= @str + ' and  MPE1.SkillId='+@RoleID            
end            
 if (@TrainingID <> 0)            
begin           
set @str= @str + ' and MPT.TrainingId in (select TrainingId from DumyTrainingReadiness where sessionid = '''+@sessionid
    set @str= @str + ''')'       
end            
exec (@str)           
           
end

Procedure which accepts parameters and checks if the parameter is not 0 or null ,gets result based on parameter passed

//This Procedure accepts 5 parameters ,even if null or 0 is passed of any parameters it returs result.
//
Create procedure usp_testsp
@ChannelID nvarchar(100),     
@DealerID nvarchar(100),       
     
@AreaID nvarchar(100),       
     
@ZoneID nvarchar(100),      
     
@RoleID nvarchar(100)     
     
     
as     
     
SELECT Distinct MZ.ZONE,MA.AREANAME as AO,D.Code as DealerCode,D.Name as DealerName,MP1.EmployeeCode,     
(MP1.FirstName + ' ' + MP1.LastName) as Name,MS.SkillName as empRole,MT.Code,MPT.TrainingCompletionDate
FROM MAS_AREA MA        
INNER JOIN MAS_ZONE MZ ON MA.ZONEID=MZ.ID      
      
INNER JOIN DEALER D ON MA.ID=D.AREACODEID       
INNER JOIN DEALERLOCATION  DL ON D.ID=DL.DEALERID  and DL.IsActive=1     
INNER JOIN DEALERCHANNELMAPPING DM ON D.ID=DM.DEALERID and D.IsActive=1     
inner join ManPowerTraining MPT on DL.ID=MPT.ManPowerId and MPT.IsActive=1     
INNER JOIN LOCATIONMANPOWERASSOCIATON LMA ON LMA.MANPOWERID = MPT.MANPOWERID and  LMA.ENDDATE IS NULL       
inner join  ManPower MP1 on MP1.ID=MPT.ManPowerId and MP1.IsActive=1     
inner join  ManPowerExperience MPE1 on MP1.ID=MPE1.ManPowerId and MPE1.IsActive=1     
inner join  Mas_Skills MS on MS.ID=LMA.SkillID and MS.IsActive=1     
inner join Mas_Training MT on MT.ID=MPT.TrainingId and MT.IsActive=1    
where   
       
   
 (@RoleID=0 OR @RoleID=NULL OR MPE1.SKILLID =@RoleID)   
AND DM.CHANNELID=@ChannelID     
 AND (@AREAID=0 OR @AREAID=NULL OR MA.ID=@AREAID)     
 AND (@DEALERID=0 OR @DEALERID= NULL OR D.ID=@DEALERID)     
AND (@ZONEID=0 OR @ZONEID=NULL OR MZ.ID=@ZONEID)    

order BY MZ.ZONE,MA.AREANAME

Calling Required field validator from Code behind

//.aspx page

<asp:dropdownlist appenddatabounditems="true" autopostback="True" datatextfield="ChannelNo" datavaluefield="Id" id="ddlChannel" onselectedindexchanged="ddlChannel_SelectedIndexChanged" runat="server">
 </asp:dropdownlist>
  &nbsp;<asp:requiredfieldvalidator controltovalidate="ddlChannel" cssclass="ErrorMessage" errormessage="Select Channel Name" forecolor="" id="RequiredFieldValidator1" initialvalue="--Select--" runat="server" setfocusonerror="true" validationgroup="GnReport">
</asp:requiredfieldvalidator>

//.cs page

call it inside button click

   if (ddlChannel.Text == "0")
 
{

  RequiredFieldValidator1.Validate();
   
 RequiredFieldValidator1.IsValid = false;
 
 RequiredFieldValidator1.Visible = true;
 
  RequiredFieldValidator1.Enabled = true;
 
  RequiredFieldValidator1.ErrorMessage = "Select Channel Name.";
 
  return;
                }