Translate

C# winform read write any file to Database

Monday, December 26, 2016 0




Browse File for Save to DB

string fileName="";
 object file;
 string ext="";
 private void LoadFile()
        {
            OpenFileDialog OpenFileDialog = new OpenFileDialog();
            OpenFileDialog.Title = "Open File...";
            //OpenFileDialog.Filter = "Binary File (*.bin)|*.bin";
            OpenFileDialog.InitialDirectory = @"C:\";
            if (OpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                byte[] file;
                using (var stream = new FileStream(OpenFileDialog.FileName, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        file = reader.ReadBytes((int)stream.Length);
                    }
                }
                fileName = OpenFileDialog.FileName;
                file = file;
                ext = Path.GetExtension(OpenFileDialog.FileName);
            }
        } 
 
During Save operation use file object as byte array and save to database.
for easy save use entity framework .
where i have select datatype for sql server is varbinary(MAX).
 
 View File to user
 
private void ViewDocument(Label lblloc, string fileName)
        {
            try
            {
                if (file == null)
                {
                    MessageBox.Show("No file for view");
                    return;
                }

                SaveFileDialog savefile = new SaveFileDialog();
                // set a default file name
                savefile.FileName = fileName + ext;
                // set filters - this can be done in properties as well
                savefile.Filter = "All files (*.*)|*.*";

                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    // using (StreamWriter sw = new StreamWriter(savefile.FileName))
                    //      sw.WriteLine("Hello World!");

                    ByteArrayToFile(savefile.FileName, file as byte[]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


  public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream =
                   new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
                                            System.IO.FileAccess.Write);
                // Writes a block of bytes to this stream using data from
                // a byte array.
                _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

                // close file stream
                _FileStream.Close();

                return true;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}",
                                  _Exception.ToString());
            }

            // error occured, return false
            return false;
        }


C# Open XML SDK ,Excel Read,Write

Category : 0

Installation :
1.https://www.microsoft.com/en-us/download/details.aspx?id=30425
or
2. https://www.nuget.org/packages/DocumentFormat.OpenXml/

Adding Reference :

  • DocumentFormat.OpenXml
  • WindowsBase
 Ref : https://msdn.microsoft.com/en-us/library/office/bb456488.aspx


Write Excel

public void ExportDataTable(DataTable table, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();

                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                //foreach (System.Data.DataTable table in ds.Tables)
               // {

                    var sheetPart = workbook.WorkbookPart.AddNewPart();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    uint sheetId = 1;
                    if (sheets.Elements().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                    sheets.Append(sheet);

                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List columns = new List();
                    foreach (System.Data.DataColumn column in table.Columns)
                    {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }


                    sheetData.AppendChild(headerRow);

                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

                //}
            }
        }
   





Read Excel File

     public static DataSet ExtractExcelSheetValuesToDataTable(string xlsxFilePath, string sheetName)
        {
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(xlsxFilePath, true))
            {
                //Access the main Workbook part, which contains data
                WorkbookPart workbookPart = myWorkbook.WorkbookPart;
                WorksheetPart worksheetPart = null;
                if (!string.IsNullOrEmpty(sheetName))
                {
                    Sheet ss = workbookPart.Workbook.Descendants().Where(s => s.Name == sheetName).FirstOrDefault();
                    if(ss == null)
                    {
                        throw new Exception("Sheet name not mathced");
                    }
                    worksheetPart = (WorksheetPart)workbookPart.GetPartById(ss.Id);
                }
                else
                {
                    worksheetPart = workbookPart.WorksheetParts.FirstOrDefault();
                }
                SharedStringTablePart stringTablePart = workbookPart.SharedStringTablePart;
                if (worksheetPart != null)
                {
                    Row lastRow = worksheetPart.Worksheet.Descendants().LastOrDefault();
                    Row firstRow = worksheetPart.Worksheet.Descendants().FirstOrDefault();
                    if (firstRow != null)
                    {
                        foreach (Cell c in firstRow.ChildElements)
                        {
                            string value = GetValue(c, stringTablePart);
                            dt.Columns.Add(value);
                        }
                    }
                    if (lastRow != null)
                    {
                        for (int i = 2; i <= lastRow.RowIndex; i++)
                        {
                            DataRow dr = dt.NewRow();
                            bool empty = true;
                            Row row = worksheetPart.Worksheet.Descendants().Where(r => i == r.RowIndex).FirstOrDefault();
                            int j = 0;
                            if (row != null)
                            {
                                foreach (Cell c in row.Descendants())
                                {
                                    int? colIndex = GetColumnIndex(((DocumentFormat.OpenXml.Spreadsheet.CellType)(c)).CellReference);
                                    if (colIndex > j)
                                    {
                                        dr[j] = "";
                                        j++;
                                    }

                                    if(j == 21)
                                    {
                                        // only for checking
                                    }
                                    //Get cell value
                                    string value = "";
                                   // if (c.ElementAt(0).Count() >0)
                                      //  value=  c.CellValue.Text;
                                     value = GetValue(c, stringTablePart);
                                    //if (!string.IsNullOrEmpty(value))
                                    //    empty = false;
                                    dr[j] = value;
                                    j++;
                                    if (j == dt.Columns.Count)
                                        break;
                                }

                                //foreach (Cell c in row.ChildElements)
                                //{
                                //    //Get cell value
                                //    string value = GetValue(c, stringTablePart);
                                //    //if (!string.IsNullOrEmpty(value))
                                //    //    empty = false;
                                //    dr[j] = value;
                                //    j++;
                                //    if (j == dt.Columns.Count)
                                //        break;
                                //}
                                //if (empty)
                                //    break;
                                dt.Rows.Add(dr);
                            }
                        }
                    }
                }
            }
            ds.Tables.Add(dt);
            return ds;
        }
     
        public static string GetValue(Cell cell, SharedStringTablePart stringTablePart)
        {
            if (cell.ChildElements.Count == 0) return null;
            //get cell value
            string value = cell.ElementAt(0).InnerText;//CellValue.InnerText;
            //Look up real value from shared string table
            if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
                value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            return value;
            
        }

        private static int? GetColumnIndex(string cellReference)
        {
            if (string.IsNullOrEmpty(cellReference))
            {
                return null;
            }

            //remove digits
            string columnReference = Regex.Replace(cellReference.ToUpper(), @"[\d]", string.Empty);

            int columnNumber = -1;
            int mulitplier = 1;

            //working from the end of the letters take the ASCII code less 64 (so A = 1, B =2...etc)
            //then multiply that number by our multiplier (which starts at 1)
            //multiply our multiplier by 26 as there are 26 letters
            foreach (char c in columnReference.ToCharArray().Reverse())
            {
                columnNumber += mulitplier * ((int)c - 64);

                mulitplier = mulitplier * 26;
            }

            //the result is zero based so return columnnumber + 1 for a 1 based answer
            //this will match Excel's COLUMN function
            return columnNumber;
        }







C# Winform Create Dynamic TabPage and add User Control

Tuesday, November 22, 2016 Category : 0

  List<string> openTabs = new List<string>();
  List<TabPage> openTabPages = new List<TabPage>();

  private void OpenPage(Control control, string OperationName)
        {

            if (!openTabs.Exists(m => m.ToString() == OperationName))
            {
                TabPage tb = new TabPage();
                tb.Text = OperationName;
                tb.Controls.Add(control);
                tabControl1.TabPages.Add(tb);

                // set align position
                int main_width = tabControl1.Width;
                int control_width = control.Width;
                int posX = (main_width - control_width) / 2;
                control.Location = new Point(posX, 0);

                tabControl1.SelectedTab = tb;

                openTabs.Add(OperationName);
                openTabPages.Add(tb);
            }
            else
            {
                foreach (TabPage tb in tabControl1.TabPages)
                {
                    Control ctl = tb.Controls[0];
                    if (ctl != null)
                    {
                        if (ctl.GetType() == control.GetType())
                        {
                            tabControl1.SelectedTab = tb;
                        }
                    }
                }
            }


        }

C# Winform Add Border to UserControl

Category : 0

protected override void OnPaint(PaintEventArgs e)
{

base.OnPaint(e);
int borderWidth = 3;
Color borderColor = SystemColors.AppWorkspace;
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, borderColor,
borderWidth, ButtonBorderStyle.Solid, borderColor, borderWidth,
ButtonBorderStyle.Solid, borderColor, borderWidth, ButtonBorderStyle.Solid,
borderColor, borderWidth, ButtonBorderStyle.Solid);
}


Source : https://social.msdn.microsoft.com/Forums/windows/en-US/ca9a9df3-c37e-455b-8fae-58d88ed77d90/change-border-around-usercontrol?forum=winformsdesigner
 

Fixed header and scrollable body

Tuesday, July 12, 2016 Category : 0



<div class="Top1 base">
    <table>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
          ....
        </tr>
    </table>
</div>
<div class="Top2 base">
    <table>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            </td>
            <td>5
            </td>
            <td>6
            </td>
            <td>7
          .....
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            </td>
          .....
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            </td>
          ...
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
           ....
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            ........
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            </td>
            <td>5
           ...........
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            </td>
            .....
        </tr>
        <tr>
            <td>1
            </td>
            <td>2
            </td>
            <td>3
            </td>
            <td>4
            </td>
            <td>5
            </td>
            ......
        </tr>
    </table>
</div>




.base{
    width:250px;
    overflow:scroll;
    max-height:100px;
}

.Top1
{
    overflow:hidden;
    width: 230px;
 }


$('.Top2').bind('scroll', function(){
  $(".Top1").scrollLeft($(this).scrollLeft());
});




Source : http://jsfiddle.net/A79e2/10/

ASP.NET Expand grid view

Wednesday, May 4, 2016 Category : 0

Source :  http://www.aspsnippets.com/Articles/ASPNet-Nested-GridViews-GridView-inside-GridView-with-Expand-and-Collapse-feature.aspx


<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid"
    DataKeyNames="CustomerID" OnRowDataBound="OnRowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <img alt = "" style="cursor: pointer" src="images/plus.png" />
                <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
                    <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
                        <Columns>
                            <asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />
                        </Columns>
                    </asp:GridView>
                </asp:Panel>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
    </Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gvCustomers.DataSource = GetData("select top 10 * from Customers");
        gvCustomers.DataBind();
    }
}


protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string customerId = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
        GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
        gvOrders.DataSource = GetData(string.Format("select top 3 * from Orders where CustomerId='{0}'", customerId));
        gvOrders.DataBind();
    }
}
 
 
 
 
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>
 
 
 
 

ASP.NET C# Document Download from Database

Sunday, April 24, 2016 Category : , , 0


Load document byte from sql server database. save it to temporary storeage , and view in browser.

public void Download() {

string fileName = "abc.doc";
string _path = Request.PhysicalApplicationPath + "Temp/" + fileName;

byte[] filebyte = new byte[0]; // load from database

File.WriteAllBytes(_path, filebyte );

oR.showReportAjax(ResolveUrl("~/Temp/" + fileName), this.GetType(), this, UpdatePanel1);

}

public void showReportAjax(string pageUrl, Type cType, Page oPage, Control ctrl)
{
string url = ResolveClientUrl(pageUrl) ;

ScriptManager.RegisterStartupScript(ctrl, typeof(string), "redirect", "window.open('" + url + "');", true);

} 
 

Method 2


System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", 
                           "attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath("FileDownload.csv"));
        response.Flush();    
        response.End();

 

Powered by Blogger.