Translate

Home > 2016

2016

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();

 

ASP.NET Jquery Auto complete with selected value

Friday, March 25, 2016 Category : 0


 function InitAutoCompl3() {

                                         
                                             $("#<%=txtAccountName.ClientID %>").autocomplete({
                                                 source: function (request, response) {
                                                     $.ajax({
                                                         url: '<%=ResolveUrl("~/DataWebService.asmx/GetAccounts2") %>',
                                                         data: "{ 'prefixText': '" + request.term + "'}",
                                                         dataType: "json",
                                                         type: "POST",
                                                         contentType: "application/json; charset=utf-8",
                                                         success: function (data) {

                                                             response($.map(data.d, function (item) {
                                                                 return {
                                                                     label: item.split('~')[1],
                                                                     val: item.split('~')[0]
                                                                 }
                                                             }))
                                                         },
                                                         error: function (response) {
                                                             alert(response.responseText);
                                                         },
                                                         failure: function (response) {
                                                             alert(response.responseText);
                                                         }
                                                     });
                                                 },
                                                 select: function (e, i) {
                                                     $("#<%=HFAcId2.ClientID %>").val(i.item.val);
                                                 },
                                                 minLength: 1
                                             });
                                     };


ASP.NET call Java function in every async postback

Category : , 0

 $(document).ready(function () {
                                         var prm = Sys.WebForms.PageRequestManager.getInstance();
                                         prm.add_initializeRequest(InitializeRequest);
                                         prm.add_endRequest(EndRequest);

                                         // Place here the first init of the autocomplete
                                         InitAutoCompl3();  // in web user control
                                     });

                                     function InitializeRequest(sender, args) {
                                     }

                                     function EndRequest(sender, args) {
                                         // after update occur on UpdatePanel re-init the Autocomplete
                                         InitAutoCompl3();
                                     }

Quick Book 2014 C# Voucher Posting And Get

Monday, March 14, 2016 Category : 0

Required : SDK 13.0
Download link : https://developer.intuit.com/docs/0250_qb/0020_get_set_up/sdk_downloads
https://developer.intuit.com/Downloads/Restricted?filename=qbsdk130.exe

Sample Experimental Project :
https://onedrive.live.com/redir?resid=7D3B49FB4453E77A!1431&authkey=!AANhtiemRiGCDwk&ithint=file%2crar


Reference Guide: 

http://www.nullskull.com/a/1568/c-net-application-with-quickbooks-desktop-edition.aspx
https://mukarrammukhtar.wordpress.com/quickbooks-with-net/
http://qbblog.ccrsoftware.info/2010/03/quickbooks-add-on-programs-sdk/

HTML FileBrowser Image Preview

Wednesday, February 3, 2016 Category : , , 0


HTML



<div class="form-group">
                                <label class="control-label col-md-3" for="inputWarning"> Image 1 </label>
                                <div class="col-md-4">
                                    <input id="exampleInputFile1" name="ImagePath" type="file">
                                    <b>Live Preview</b>
                                    <br />
                                    <div id="dvPreview1">
                                    </div>
                                </div>
                            </div>



Java Script




  window.onload = function () {

        LoadTempData();

        var fileBrowser = document.getElementById("exampleInputFile1");
        fileBrowser.onchange = function () {
            LoadImage('1', fileBrowser);
        }


        var fileBrowser2 = document.getElementById("exampleInputFile2");
        fileBrowser2.onchange = function () {
            LoadImage('2', fileBrowser2);
        }


        var fileBrowser3 = document.getElementById("exampleInputFile3");
        fileBrowser3.onchange = function () {
            LoadImage('3', fileBrowser3);
        }

        var fileBrowser4 = document.getElementById("exampleInputFile4");
        fileBrowser4.onchange = function () {
            LoadImage('4', fileBrowser4);
        }


        var fileBrowser5 = document.getElementById("exampleInputFile5");
        fileBrowser5.onchange = function () {
            LoadImage('5', fileBrowser5);
        }

    };





function LoadImage(idNo, fileBrowser)
    {

        if (typeof (FileReader) != "undefined") {
            var dvPreview = document.getElementById("dvPreview" + idNo);
            dvPreview.innerHTML = "";
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
            for (var i = 0; i < fileBrowser.files.length; i++) {
                var file = fileBrowser.files[i];
                if (regex.test(file.name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {

                        //var img = document.createElement("IMG");
                        //img.height = "100";
                        //img.width = "100";
                        //img.src = e.target.result;
                        //dvPreview.appendChild(img);

                        var image = new Image();
                        image.src = e.target.result;
                        image.onload = function () {
                            if(image.width != 680 || image.height!=850)
                            {
                                alert('Image size not valid');

                                //debugger;
                                //fileBrowser.outerHTML = fileBrowser.outerHTML;
                                //$('#' + id).html($('#' + id).html());
                                fileBrowser.value = "";

                            } else {
                                image.height = "100";
                                image.width = "150";
                                //img.src = e.target.result;
                                dvPreview.appendChild(image);
                            }
                        };

                    }
                    reader.readAsDataURL(file);
                } else {
                    alert(file.name + " is not a valid image file.");
                    dvPreview.innerHTML = "";
                    return false;
                }
            }
        } else {
            alert("This browser does not support HTML10 FileReader.");
        }
    }


ASP.NET MVC Jquery Image and Text Save

Category : , 0




  $("#btnAdd").click(function (e) {
        e.preventDefault();
        //$("#form1").submit();
        var file1;
        if (document.getElementById("exampleInputFile1").files.length > 0)
            file1 = document.getElementById("exampleInputFile1").files[0];

        var file2;
        if (document.getElementById("exampleInputFile2").files.length > 0)
            file2 = document.getElementById("exampleInputFile2").files[0];


        var file3;
        if (document.getElementById("exampleInputFile3").files.length > 0)
            file3 = document.getElementById("exampleInputFile3").files[0];

        var file4;
        if (document.getElementById("exampleInputFile4").files.length > 0)
            file4 = document.getElementById("exampleInputFile4").files[0];

        var file5;
        if (document.getElementById("exampleInputFile5").files.length > 0)
            file5 = document.getElementById("exampleInputFile5").files[0];
      

        var formData = new FormData();
        formData.append("MainGroupId", $("#MainGroup").val());
        formData.append("MainGroupName", $("#MainGroup option:selected").text());

        formData.append("SubGroupId", $("#SubGroup").val());
        formData.append("SubGroupName", $("#SubGroup option:selected").text());

        formData.append("NewBrandId", $("#NewBrandId").val());
        formData.append("NewBrandName", $("#NewBrandId option:selected").text());

        formData.append("NewCategoryId", $("#NewCategoryId").val());
        formData.append("NewCategoryName", $("#NewCategoryId option:selected").text());

        formData.append("NewColorId", $("#NewColorId").val());
        formData.append("NewColorName", $("#NewColorId option:selected").text());

        formData.append("IsActive", $("#IsActive").val());
        formData.append("Description", $("#Description").val());

        formData.append("Image1", file1);
        formData.append("Image2", file2);
        formData.append("Image3", file3);
        formData.append("Image4", file4);
        formData.append("Image5", file5);

        formData.append("OperationType", $("#hdnType").val());

        $.ajax({
            type: "POST",
            url: _urlBase + '/ProductManage/AddTempProduct',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {

                if (data.ResultState == true) {
                    // done
                }
                else if (data.ResultState == false)
                    ShowMessage(data.SqlError);

            },
            error: function (error) {
                alert("errror");
            }
        });

    });





Backend C# code


[HttpPost]
        public JsonResult AddTempProduct()
        {
            Result r = new Result();
            try
            {
                ArticlePOCO article = new ArticlePOCO();


                article.MainGroupId = Request.Form["MainGroupId"];
               

                string OperationType = Request.Form["OperationType"];

                
    if (Request.Files.Count > 0)
                    {
                        if (Request.Files["Image1"] != null)
                        {
                            article.Image1 = Request.Files["Image1"];
                        }
                        if (Request.Files["Image2"] != null)
                        {
                            article.Image2 = Request.Files["Image2"];
                        }
                        if (Request.Files["Image3"] != null)
                        {
                            article.Image3 = Request.Files["Image3"];
                        }
                        if (Request.Files["Image4"] != null)
                        {
                            article.Image4 = Request.Files["Image4"];
                        }
                        if (Request.Files["Image5"] != null)
                        {
                            article.Image5 = Request.Files["Image5"];
                        }
                    }
     
                

                
            }
            catch (Exception ex)
            {
                r.ResultState = false;
                r.SqlError = ex.Message;
            }

            System.Web.Mvc.JsonResult jsonRe = new System.Web.Mvc.JsonResult()
            {
                Data = r,
                JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.DenyGet
            };

            return jsonRe;

        }

ASP.NET Ajax Control Calenter Extender CSS

Monday, February 1, 2016 Category : 0

Some time outer table class poperty change the calender style , then we can fix it by applying this css.





.ajax__calendar table
{
margin:0px !important;
width:auto !important;
padding-left:0px !important;

}

.ajax__calendar table td
{
padding-left:2px !important;
padding-right:2px !important;
width:auto !important;
}
.ajax__calendar table th
{
padding-left:0px !important;
width:auto !important;
}
.ajax__calendar_container table
{
margin:0px !important;
padding:0px !important;
}

C# SQL Connection Best Connection Practice

Sunday, January 17, 2016 0


namespace Repository
{
    public class SQLRepository
    {

        DbConnector dbCon = new DbConnector();

        #region Query Execute
        public Result ExecuteQuery(string SQL)
        {
            Result oResult = new Result();
            SqlCommand oCmd = null;

            try
            {

                if (dbCon.Connect != null)
                {
                    dbCon.OpenConnection();
                    oCmd = new SqlCommand(SQL, dbCon.Connect);
                    oCmd.ExecuteNonQuery();
                    oResult.ResultState = true;
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

        public Result ExecuteQuery(List SQL)
        {
            Result oResult = new Result();
            SqlTransaction oTransaction = null;
            SqlCommand oCmd = null;

            try
            {

                if (dbCon.Connect != null)
                {
                    dbCon.OpenConnection();
                    oTransaction = dbCon.Connect.BeginTransaction();
                    foreach (string s in SQL)
                    {
                        oCmd = new SqlCommand(s, dbCon.Connect);
                        oCmd.Transaction = oTransaction;
                        oCmd.ExecuteNonQuery();
                        oResult.ResultState = true;
                    }
                    oTransaction.Commit();
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
                if (oTransaction != null)
                    oTransaction.Rollback();
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

        public Result ExecuteQueryParam(List SQL)
        {
            Result oResult = new Result();
            SqlTransaction oTransaction = null;
            SqlCommand oCmd = null;

            try
            {

                if (dbCon.Connect != null)
                {
                    dbCon.OpenConnection();
                    oTransaction = dbCon.Connect.BeginTransaction();
                    foreach (SQLQuery s in SQL)
                    {
                        oCmd = new SqlCommand(s.sql, dbCon.Connect);
                        oCmd.Transaction = oTransaction;

                        foreach (SQLParam param in s.Param)
                        {
                            SqlParameter picparameter = new SqlParameter();
                            picparameter.SqlDbType = param.DbType; //SqlDbType.Image;
                            picparameter.ParameterName = param.ParamName; //"@PIC";
                            picparameter.Value = param.ParamValue;
                            oCmd.Parameters.Add(picparameter);
                        }

                        oCmd.ExecuteNonQuery();
                        oResult.ResultState = true;
                    }
                    oTransaction.Commit();
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
                if (oTransaction != null)
                    oTransaction.Rollback();
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

        #endregion

        public Result Select(string SQL)
        {
            Result oResult = new Result();
            SqlCommand oCmd = null;
            try
            {

                if (dbCon.Connect != null)
                {
                    oCmd = new SqlCommand(SQL, dbCon.Connect);
                    oCmd.CommandTimeout = 0;
                    SqlDataAdapter adapter = new SqlDataAdapter(oCmd);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    oResult.ResultState = true;
                    oResult.Data = dt;
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

    }

    public class DbConnector
    {

        private SqlConnection connection;

        public DbConnector()
        {
            connection = new SqlConnection(GlobalConnection());
        }

        public string GlobalConnection()
        {

            //string entityConnectionString = ConfigurationManager.ConnectionStrings["ERPEntities"].ConnectionString;
            //string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;
            //return providerConnectionString;

            string str = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            //ConfigurationSettings.AppSettings["CNN"];
            return str;
        }

        public SqlConnection Connect
        {
            get { return connection; }
        }

        public ConnectionState OpenConnection()
        {
            Connect.Open();
            return ConnectionState.Open;
        }

        public ConnectionState CloseConnection()
        {
            Connect.Close();
            return ConnectionState.Closed;
        }
    }

    public class SQLQuery
    {
        public string sql { get; set; }
        public List Param = new List();
    }

    public class SQLParam
    {
        public string ParamName { get; set; }
        public byte[] ParamValue { get; set; }
        public SqlDbType DbType { get; set; }
    }

    //public class Result
    //{
    //    public bool ResultState;
    //    public string SqlError;
    //    public DataTable Data;
    //}

}


Powered by Blogger.