Friday, May 3, 2019

C# ASP.NET image Read/Write as BLOB varbinary (MAX)

C# ASP.NET image Read/Write as BLOB varbinary (MAX)



DATABASE
CREATE TABLE [dbo].[AngularEmployee](
       [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
       [FirstName] [nvarchar](50) NULL,
       [LastName] [nvarchar](50) NULL,
       [EmpCode] [nvarchar](50) NULL,
       [Position] [nvarchar](50) NULL,
       [Picture] [varbinary](max) NULL,
 CONSTRAINT [PK_AngularEmployee] PRIMARY KEY CLUSTERED
(
       [EmployeeID] 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

C# ASP CODE
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="SAVE" runat="server" Text="Button" OnClick="SAVE_Click" />
        <br />
        <asp:Button ID="VIeW" runat="server" Text="View Image" OnClick="VIEW_Click" />
        <br />
        <asp:Image ID="imgTest" runat="server" />
    </div>

    </form>

C# CODE

protected void SAVE_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string contentType = FileUpload1.PostedFile.ContentType;
        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);

                using (SqlConnection con = new SqlConnection("Data Source=????;Initial Catalog=??????;User ID=??????;Password=??????;Connection Timeout=900"))
                {
                    using (SqlCommand cmd = new SqlCommand("update [dbo].[AngularEmployee] set LastName=@L1 , Position=@P1, Picture = @Picture where EmployeeID='"+ TextBox1.Text + "'", con))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@L1", filename);
                        cmd.Parameters.AddWithValue("@P1", contentType);
                        cmd.Parameters.AddWithValue("@Picture", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
    }

    protected void VIEW_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=????;Initial Catalog=??????;User ID=??????;Password=??????;Connection Timeout=900");
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter("select * from [dbo].[AngularEmployee] where EmployeeID='" + TextBox1.Text + "'", con);
        da.Fill(dt);
        byte[] bytes = (byte[])dt.Rows[0]["Picture"];
        string type = Convert.ToString(dt.Rows[0]["Position"]);

        string str64 = Convert.ToBase64String(bytes);

        imgTest.ImageUrl = "data:" + type + ";base64," + str64;
    }

Thursday, February 28, 2019

An error occurred while enumerating the groups. the group could not be found. : Get the Bad groups name.



Problem: An error occurred while enumerating the groups. the group could not be found.


In c#.net exception occurs. 
  1. Then way to find the bad group. Below is the code.
  2. First get all groups for a user in AD.
  3. Then loop through and get the object of Group Name. If not found then it will be null.
  4. Else it is a valid Group.
  5. "nullgrpname" variable contains all Bad Groups.


private void GetBadGroups(string groupName, string userName)
    {


        System.DirectoryServices.AccountManagement.PrincipalContext ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(
                                        System.DirectoryServices.AccountManagement.ContextType.Domain, "DOMAIN");
        // find a user
        System.DirectoryServices.AccountManagement.UserPrincipal uPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, userName);
        string res = "";
        var sroles = uPrincipal.GetAuthorizationGroups();
        if (sroles != null && sroles.Count() > 0)
        {
            int i = 0;
            List<string> rs = new List<string>();
            while (i < sroles.Count()) //unknown error happens on some groups
            {
                try
                {
                    var role = sroles.ElementAt(i);
                    if (role != null && role.Name != null)
                        rs.Add(role.Name.ToUpper());
                }
                catch
                {
                    res += ("A bad group has been found on user:" + userName);
                }
                i++;
            }
            string[] roles = rs.ToArray();
            string ab1 = roles[0];
            ////   ---------------------------------
            string nullgrpname = "";
            foreach (string name in roles)
            {
                groupName = name;
                // set up domain context
                PrincipalContext ctx1 = new PrincipalContext(ContextType.Domain, "DOMAIN");

                // find a user
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx1, userName);

                // find the group in question
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx1, groupName);
                if (group == null)
                {
                    nullgrpname += groupName + ";";
                }

                if (user != null && group != null)
                {
                    // check if user is member of that group
                    if (user.IsMemberOf(group))
                    {
                        // do something.....
                    }
                }
            }
        }
    }

Tuesday, December 18, 2018

jQgrid with common search textbox maually with Dynamic columns showing with freeze as well.



solution For:

  1. Freeze jqGrid columns
  2. Unload/Unbind grid.
  3. Search by Textbox for all rows and columns

JQ grid version: v5.3.2

HTML
<div class="pull-right" style="font-weight: normal;font-style: normal;">
   <input type="text" ng-model="srchCnsldRcpt" placeholder="Search Here" ng-keyup="bindJqGrid('cnsld', Rcpt)" />
 </div>
                            </td>
<%--jq grid--%>

<table id="gvCnsldRcpt"></table>

JavaScript

$scope.bindJqGrid = function (key, p1) {
        try {
            if (key == 'cnsld') {
                $.jgrid.gridUnload("#gvCnsldRcpt");
                var colName = Object.keys(p1[0]);
                var colMdl = [];
                var p2 = [];
                if (typeof $scope.srchCnsldRcpt != 'undefined' && $scope.srchCnsldRcpt.trim() != '') {
                    for (var x = 0; x < p1.length; x++) {
                        var cnt = 0;
                        for (var j = 0; j < colName.length; j++) {
                            var cnm = p1[x][colName[j]] + "";
                            var fnd = cnm.toLowerCase().search($scope.srchCnsldRcpt.toLowerCase().trim());
                            if (parseInt(cnt) == 0 && parseInt(fnd) >= 0) {
                                p2.push(p1[x]); cnt = 1;
                            }
                        }
                    }
                }
                else
                    p2 = p1;
                for (var i = 0; i < colName.length; i++) {
                    var jq = {};
                    jq.name = colName[i];
                    jq.index = colName[i];
                    if (i == 0 || i == 1) {
                        jq.frozen = true;
                        jq.width = 100;
                        jq.search = true;
                    }
                    else {
                        jq.width = 60;
                    }
                    colMdl.push(jq);
                }
                $("#gvCnsldRcpt").jqGrid({
                    datatype: 'local',
                    data: p2,
                    gridview: true,
                    colNames: colName,
                    colModel: colMdl,
                    height: "120",
                    shrinkToFit: false,
                    width: 620,
                    loadError: function (xhr, status, error) {
                        alert('error');
                    }
                });
                $("#gvCnsldRcpt").jqGrid("setFrozenColumns");
            }
        }
        catch (ex) {
            alert(ex.message);
        }
    }

Wednesday, November 21, 2018

HTML table to convert to XLSX excel file javascript jquery ASP.net



HTML table to convert to XLSX excel file javascript jquery

file link: https://unpkg.com/xlsx@0.14.1/dist/xlsx.full.min.js
https://github.com/sheetjs/js-xlsx
https://freakyjolly.com/demo/jsonToXLS/
https://stackoverflow.com/questions/39475474/how-to-export-or-convert-json-to-excel-in-angularjs

JS file Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jsontohtml.aspx.cs" Inherits="jsontohtml" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="export/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="export/xlsx.full.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <script>

        function expt() {
  function tabletoexcel() {
            var tbl = document.getElementById('sheetjs');
            /* File Name */
            var filename = "FreakyJSON_To_XLS.xlsx";

            /* Sheet Name */
            var ws_name = "FreakySheet";

            if (typeof console !== 'undefined') console.log(new Date());
            var wb = XLSX.utils.book_new(),
                ws = XLSX.utils.table_to_sheet(tbl);

            /* Add worksheet to workbook */
            XLSX.utils.book_append_sheet(wb, ws, ws_name);

            /* Write workbook and Download */
            if (typeof console !== 'undefined') console.log(new Date());
            XLSX.writeFile(wb, filename);
            if (typeof console !== 'undefined') console.log(new Date());

        }

    </script>

        <button onclick="tabletoexcel();return false;">export to table</button><br />
        <table id="sheetjs">
            <tr><td colspan="2">Ashwini</td><td colspan="4">Sharma</td></tr>
<tr><td>Sai</td><td>Kumar</td><td>ved</td><td>kumar</td><td>t</td><td>J</td><td>S</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td></tr>
<tr><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td></tr>

</table>