Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, April 20, 2026

Selenium Automation motif-select shadow dom with select all and given options

In this post I want to share one of the problem faced with selenium and motif-select with shadow DOM. I tried many options but couldn't get the required, as per the requirement here are the two methods I wrote
public void SelectMultipleOptions(IWebDriver driver, WebDriverWait wait, string sectionLabel, string commaSeparatedValues)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver; var values = commaSeparatedValues .Split(',') .Select(v => v.Trim()) .Where(v => !string.IsNullOrEmpty(v)) .ToList(); // Open dropdown dynamically var dropdown = driver.FindElement(By.XPath($"//span[contains(text(),'{sectionLabel}')]/following::motif-select[1]")); dropdown.Click(); foreach (var val in values) { wait.Until(d => { return (bool)js.ExecuteScript(@" const section = arguments[0]; const select = [...document.querySelectorAll('motif-select')] .find(el => el.closest('.pushdown-filter')?.innerText.includes(section)); return select && select.querySelectorAll('motif-select-option').length > 0; ", sectionLabel); }); var element = js.ExecuteScript(@" const label = arguments[0]; const section = arguments[1]; const select = [...document.querySelectorAll('motif-select')] .find(el => el.closest('.pushdown-filter')?.innerText.includes(section)); if (!select) return null; const options = [...select.querySelectorAll('motif-select-option')]; return options.find(o => o.textContent.trim() === label ); ", val, sectionLabel); if (element != null) { js.ExecuteScript(@" const opt = arguments[0]; const cb = opt.shadowRoot?.querySelector('motif-checkbox'); if (cb) cb.click(); else opt.click(); ", element); } else { Console.WriteLine($"[WARN] Option not found: {val}"); } } // Close dropdown try { dropdown.SendKeys(Keys.Escape); } catch { js.ExecuteScript("document.body.click();"); } }

Tuesday, January 22, 2013

Display images using entity framework along with MVC4


Create a table in SQL server as follows

USE [forumDB1]
GO

/****** Object:  Table [dbo].[users]    Script Date: 01/23/2013 11:25:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[users](
            [userID] [int] NOT NULL,
            [EmailID] [varchar](50) NOT NULL,
            [Password] [varchar](50) NOT NULL,
            [FirstName] [varchar](50) NOT NULL,
            [LastName] [varchar](50) NULL,
            [JoinedDate] [datetime] NOT NULL,
            [usrImage] [image] NULL,
PRIMARY KEY CLUSTERED 
(
            [userID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
            [EmailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO










After all select your HomeController and change as follows

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        forumDB1Entities dbentity = new forumDB1Entities();
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View(dbentity);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


Also change your view as follows

 @model displaydatausingEF.Models.forumDB1Entities
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
       
    </p>
    <table>
        <tr>
            <th>
                Employee ID
            </th>
            <th>
                Email ID
            </th>
            <th>
                Password
            </th>
            <th>
                &nbsp;First Name
            </th>
            <th>
                &nbsp;Last Name
            </th>
            <th>
                Joined Date
            </th>
            <th>
                Picture
            </th>
        </tr>
        @foreach (var item in Model.users)
        {
            <tr>
                <td>
                    &nbsp;&nbsp;@item.userID
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.EmailID
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.Password
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.FirstName
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;@item.LastName
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;@item.JoinedDate
                </td>
                <td>
                    <img src="@Url.Action(" temp_src="@Url.Action("GetPhoto", new { photoId = item.userID })" />
                </td>
            </tr>
        }
    </table>
</body>
</html>


This will initially give output as follows



Now we will implement the code to show image, add this code to your HomeController

 public ActionResult GetPhoto(int usrID)
        {
            byte[] photo = null;
            var v = dbentity.users.Where(p => p.userID == usrID).Select(img => img.usrImage).FirstOrDefault();
            photo = v;
            return File(photo, "image/jpeg");
        }

Now re-run the application


Happy coding cheers

Thursday, January 3, 2013

Dynamic Data Entities Web Application with Entity Framework


In this article I will explain how we can work with Dynamic Data Entities Web Application which is available at the time of creating a project.
In this article I will show how we can implement CRUD operation without writing a single line of code, and by just un-commenting a line in Global.asax file.
The only thing you have to do is to add a reference in Global.asax file with your project name you created. As my project name dynamicdataentities I will add this as a reference as follows
using dynamicdataentities;


The only thing you have to do after this is to un-comment this line of code from Global.asax file
DefaultModel.RegisterContext(typeof(YourDataContextType), new ContextConfiguration() { ScaffoldAllTables = false });

You have to replace this with the following
DefaultModel.RegisterContext(typeof(codeDBEntities), new ContextConfiguration() { ScaffoldAllTables = true });

Here codeDBEntities is nothing but the connection string which is available in Web.config file or you can find it in Model.edmx

First let us create a project by selecting ASP.NET Dynamic Data Entities Web Application as follows



This will create a project with a Master page, a Default page, a Global.asax file along with script and css.
Now let us add Ado.NET Entity Data Model as we did in our last article



As I am already having an connection I am not showing how to add connection, I will proceed with what I have







Open Global.asax file from the solution explorer



You can find some code with comments, we will un-comment the one we needed as follows



Here in place of YourDataContextType you have to replace your context type which will be available in web.config or in Model.edmx





Now run your application



As I integrated 2 tables it is showing those tables, select the required to perform CRUD operations.
I selected Employee and the details are as follows


In the department dropdown you can find out the entire department listed as follows



If I select any that corresponding details were shown as follows



Inserting details to Employee table, if you select Insert New Item it will display as follows



Edit Update screen



Deleting a record:

Before delete: I will delete one of the record


Delete:


After delete:


 Viewing Employees from Department



Details of selected Employee


Any comments welcome..

Please do feel free to ask for any queries...

Thursday, December 27, 2012

Implementing CRUD operation in MySql using Entity Framework

In the last two blogs I showed how we can implement CRUD operations using Entity Framework using SQL  database, now I would like to show you how we can implement the same using MySql database.

creation of table and stored procedures are left as it is almost same as per we did in SQL.

Download

Problem faced :

Before doing this I would like to tell a few problems that I faced

  • While mapping stored procedures from the model I am unable to assign the parameters as per we did in SQL server.
  • Generally in SQL while assigning parameters we write as follows                                                                        var ietsParameterEmpAddress = new MySqlParameter("@EmpAddress", txtAddress.Text); // We use @ here as we assign parameters inside stored procedure with @ symbol. In similar way I tried the same by replacing @ with _ as we use _ symbol for assigning variables in Mysql stored procedures.
  • Then I called the stored procedure as follows like we did in our earlier blogs. entities.ExecuteStoreCommand("uspInsertUsers _UserName,_Password,_FirstName,_LastName)", userName,password,FirstName,LastName);
  • After executing and trying to execute command i got an exception as You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'uspInsertUsers 'Dorababu','sae','Dorababu','M'' at line 
For the first one as per explained here Entity we can insert the data with out mapping stored procedures by using ExecuteStoreCommand and other.

For the later we have to replace _ with ? so our parameters should be passed like this

var ietsParameterEmpAddress = new MySqlParameter("?EmpAddress", txtAddress.Text);

Then ExecuteStoreCommand should be like as follows

entities.ExecuteStoreCommand("CALL uspInsertUsers(?UserName,?Password,?FirstName,?LastName)", userName,password,FirstName,LastName);

Remaining all as per we did in our earlier blogs, the design and code  is almost same except the changes as per I said.








<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="crudEF.WebForm1" %>

<!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">
    <title>MYSQL Entity Framework</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <h2>
                CRUD operations in MYSQL using Entity Framework
            </h2>
        </center>
        <center>
            <h3>
                Display data in gridview using Entity Framework with out Mapping stored procedure
                to Model
            </h3>
            <div style="width: 800px; margin: 0 auto; float: left;">
                <asp:GridView ID="grdEmployess" runat="server" BackColor="White" BorderColor="#999999"
                    DataKeyNames="EmpID" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical">
                    <AlternatingRowStyle BackColor="#DCDCDC" />
                    <EmptyDataTemplate>
                        No record to show
                    </EmptyDataTemplate>
                    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                    <SortedAscendingCellStyle BackColor="#F1F1F1" />
                    <SortedAscendingHeaderStyle BackColor="#0000A9" />
                    <SortedDescendingCellStyle BackColor="#CAC9C9" />
                    <SortedDescendingHeaderStyle BackColor="#000065" />
                </asp:GridView>
            </div>
            <br />
            <div style="width: 800px; margin: 0 auto; float: left;">
                <h3>
                    Insert Data to table using Entity Framework with out Mapping stored procedures to
                    Model</h3>
                <table>
                    <tr>
                        <td>
                            Employee ID :
                        </td>
                        <td>
                            <asp:TextBox ID="txtEmpID" ReadOnly="true" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Employee Name :
                        </td>
                        <td>
                            <asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rqrdEmployeeName" runat="server" ErrorMessage="*"
                                ControlToValidate="txtEmployeeName" ToolTip="Employee name required" ValidationGroup="g"
                                Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Employee Address :
                        </td>
                        <td>
                            <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rqrdAddress" runat="server" ErrorMessage="*" ControlToValidate="txtAddress"
                                ToolTip="Address required" ValidationGroup="g" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                    </tr>
                    <tr align="center">
                        <td colspan="3">
                            <asp:Button ID="btnInsert" runat="server" Text="Insert" ValidationGroup="g" OnClick="btnInsert_Click" />
                        </td>
                    </tr>
                </table>
            </div>
            <br />
            <div style="width: 800px; margin: 0 auto; float: left;">
                <h3>
                    Edit and Update data using storedprocedure With out mapping it to Model</h3>
                <table>
                    <tr>
                        <td>
                            Select Employee ID :
                        </td>
                        <td>
                            <asp:DropDownList ID="ddleditEmpID" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddleditEmpID_SelectedIndexChanged">
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Employee Name :
                        </td>
                        <td>
                            <asp:TextBox ID="txtedtEmployeeName" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rqrdedtEmpName" runat="server" ErrorMessage="*" ControlToValidate="txtedtEmployeeName"
                                ToolTip="Employee name required" ValidationGroup="g1" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Employee Address :
                        </td>
                        <td>
                            <asp:TextBox ID="txtedtEmpAddress" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rqrdedtEmpAddress" runat="server" ErrorMessage="*"
                                ControlToValidate="txtedtEmpAddress" ToolTip="Address required" ValidationGroup="g1"
                                Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                    </tr>
                    <tr align="center">
                        <td colspan="4">
                            <asp:Button ID="btnUpdate" runat="server" ValidationGroup="g1" Text="Update" OnClick="btnUpdate_Click" />
                        </td>
                    </tr>
                </table>
            </div>
            <br />
            <div style="width: 800px; margin: 0 auto; float: left;">
                <h3>
                    Delete data using storedprocedure With out mapping it to Model</h3>
                <table>
                    <tr>
                        <td>
                            Select Employee ID to Delete :
                        </td>
                        <td>
                            <asp:DropDownList ID="ddlEmpID" runat="server">
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                    </tr>
                    <tr align="center">
                        <td colspan="2">
                            <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
                        </td>
                    </tr>
                </table>
            </div>
        </center>
    </div>
    </form>
</body>
</html>

aspx.cs


using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

namespace crudEF
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        efdbEntities entities = new efdbEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                checkMax();
                loadGrid();
                bindDDL();
            }
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            Page.Validate("g");

            if (Page.IsValid)
            {
                var ietsParameterID = new MySqlParameter("?ID", System.Data.SqlDbType.Int);
                ietsParameterID.Value = Convert.ToInt16(txtEmpID.Text);
                var ietsParameterEmpName = new MySqlParameter("?EmpName", txtEmployeeName.Text);
                var ietsParameterEmpAddress = new MySqlParameter("?EmpAddress", txtAddress.Text);

                entities.ExecuteStoreCommand("CALL insertEmployee(?ID,?EmpName,?EmpAddress)", ietsParameterID, ietsParameterEmpName, ietsParameterEmpAddress);
                loadGrid();
                checkMax();
                bindDDL();
                txtAddress.Text = string.Empty;
                txtEmployeeName.Text = string.Empty;
            }
        }

        public void checkMax()
        {
            int? maxEmpID = entities.tblemployees.Max(q => (int?)q.EmpID);

            if (maxEmpID != null)
            {
                maxEmpID = maxEmpID + 1;
                txtEmpID.Text = maxEmpID.ToString();
            }
            else
            {
                maxEmpID = 1000;
                txtEmpID.Text = maxEmpID.ToString();
            }
        }

        public void loadGrid()
        {
            var selectData = entities.ExecuteStoreQuery<tblemployee>("CALL SelectEmployee").ToList();
            grdEmployess.DataSource = selectData;
            grdEmployess.DataBind();
        }

        public void bindDDL()
        {
            var display = from e in entities.tblemployees select new { e.EmpID };

            ddlEmpID.DataSource = display.ToList();
            ddlEmpID.DataTextField = "EmpID";
            ddlEmpID.DataValueField = "EmpID";
            ddlEmpID.DataBind();
            ddlEmpID.Items.Insert(0, "--Select--");

            ddleditEmpID.DataSource = display.ToList();
            ddleditEmpID.DataTextField = "EmpID";
            ddleditEmpID.DataValueField = "EmpID";
            ddleditEmpID.DataBind();
            ddleditEmpID.Items.Insert(0, "--Select--");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (ddlEmpID.SelectedItem.Text != "--Select--")
            {
                var ietsParameterID = new MySqlParameter("?ID", ddlEmpID.SelectedItem.Text);
                entities.ExecuteStoreCommand("CALL deleteEmp(?ID)", ietsParameterID);
                loadGrid();
                checkMax();
                bindDDL();
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Page.Validate("g1");
            if (Page.IsValid)
            {
                if (ddleditEmpID.SelectedItem.Text != "--Select--")
                {
                    var ietsParameterID = new MySqlParameter("?ID", System.Data.SqlDbType.Int);
                    ietsParameterID.Value = Convert.ToInt16(ddleditEmpID.SelectedItem.Text);
                    var ietsParameterEmpName = new MySqlParameter("?EmpName", txtedtEmployeeName.Text);
                    var ietsParameterEmpAddress = new MySqlParameter("?EmpAddress", txtedtEmpAddress.Text);

                    entities.ExecuteStoreCommand("CALL UpdateEmployee(?ID,?EmpName,?EmpAddress)", ietsParameterID, ietsParameterEmpName, ietsParameterEmpAddress);
                    loadGrid();
                    txtedtEmployeeName.Text = string.Empty;
                    txtedtEmpAddress.Text = string.Empty;
                }
            }
        }

        protected void ddleditEmpID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddleditEmpID.SelectedItem.Text != "--Select--")
            {
                int id = Convert.ToInt16(ddleditEmpID.SelectedValue.ToString());
                var display = from e1 in entities.tblemployees
                              where e1.EmpID.Equals(id)
                              select new { e1.Emp_Name, e1.Emp_Address };

                foreach (var v in display)
                {
                    txtedtEmployeeName.Text = v.Emp_Name;
                    txtedtEmpAddress.Text = v.Emp_Address;
                }
            }
        }
    }
}

Any comments welcome..

Feel free to ask for queries you have..


Popular Posts