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

Monday, November 24, 2014

JSON serialization error [maxJsonLength property.]

In my previous project I need to retrieve ticket  from Web service.When I request the web service it return a ticket as JSON format.Some time I need to retrieve more than 10 lacks ticket per requet.In that time I got the following error

Exception information:
Exception type: InvalidOperationException
Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Solution is 
            We need to set Maximum allowed length of json response in Web.config file 
The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).



You can set the MaxJsonLength property on your web.config
<configuration>
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>

Display image from database in Image control without using Generic Handler in ASP.Net

how to display images stored in database in ASP.Net Image control 

 byte[] bytes = (byte[])GetData("SELECT Data FROM tblFiles WHERE Id =" + id).Rows[0]["Data"];
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
        Image1.ImageUrl = "data:image/png;base64," + base64String;

A correlation name must be specified for the bulk rowset in the from clause.



A correlation name must be specified for the bulk rowset in the from clause.

While inserting image files into a SQL Server database table using the OPENROWSET function, I got the following error message from the SQL engine.
Msg 491, Level 16, State 1, Line 5
A correlation name must be specified for the bulk rowset in the from clause.
I soon realized that the error message is asking for a alias name for the OPENROWSET select statement.



A correlation name must be specified for the bulk rowset in the from clause.

While inserting image files into a SQL Server database table using the OPENROWSET function, I got the following error message from the SQL engine.
Msg 491, Level 16, State 1, Line 5
A correlation name must be specified for the bulk rowset in the from clause.
I soon realized that the error message is asking for a alias name for the OPENROWSET select statement.



Here is the t-sql script that is causing the error message :
INSERT INTO Files(fname, [file])
SELECT 'T-SQL-Enhancements-in-SQL-Server-2008', * FROM OPENROWSET(
  BULK N'C:\T-SQL-Enhancements-in-SQL-Server-2008.jpg', SINGLE_BLOB
)

And the below sql script displays how the correct statement should be built.
Take your attention on the "rs" alias name at the end of the script.
INSERT INTO Files(fname, [file])
SELECT 'T-SQL-Enhancements-in-SQL-Server-2012', * FROM OPENROWSET(
  BULK N'C:\T-SQL-Enhancements-in-SQL-Server-2012.jpg', SINGLE_BLOB
) rs

 examples
--INSERT
INSERT INTO  [dbo].[TsOnProfile]([Photo])SELECT * FROM OPENROWSET( BULK N'C:\1.png', SINGLE_BLOB) rs 

--update
update [dbo].[TsOnProfile] set[Photo]= (SELECT * FROM OPENROWSET(
  BULK N'C:\1.png', SINGLE_BLOB
) rs)

ref:
http://www.kodyaz.com/articles/correlation-name-for-bulk-rowset-in-from-clause.aspx

Tuesday, November 4, 2014

How to use ParameterBuilder with BeginGroup and EndGroup

Summary

Use this methods when you want to group search queries.

The query will be formatted to something like this:

Select * from Survey_Customer where SurveyHeaderID = XXX And ( (FirstName=xxx) or (LastName=xxx) or ...))



       TList<SurveyCustomer> scList = new TList<SurveyCustomer>();

            SurveyCustomerParameterBuilder pb = new SurveyCustomerParameterBuilder();
            pb.AppendEquals(SurveyCustomerColumn.SurveyHeaderId, surveyHeaderId.ToString());            
              
            pb.BeginGroup("And");
            pb.Junction = ""; // need this empty space after calling BeginGroup
            pb.AppendLike(SurveyCustomerColumn.Company, "%" + keyword + "%");
            pb.Junction = "or";
            pb.AppendEquals(SurveyCustomerColumn.FirstName, keyword);
            pb.Junction = "or";
            pb.AppendEquals(SurveyCustomerColumn.LastName, keyword);
            pb.Junction = "or";
            pb.AppendEquals(SurveyCustomerColumn.EmailAddress, keyword);
            pb.Junction = "or";
            pb.AppendLike(SurveyCustomerColumn.Comments, "%" + keyword + "%");
            pb.Junction = "or";
            pb.AppendLike(SurveyCustomerColumn.Note1, "%" + keyword + "%");
            pb.Junction = "or";
            pb.AppendLike(SurveyCustomerColumn.Url, "%" + keyword + "%");
            try // this needs to go in a try catch since db is expecting a long and user might type in a 'string'
            {
                long surveyCustomerId = long.Parse(keyword);
                pb.AppendEquals(SurveyCustomerColumn.SurveyCustomerId, surveyCustomerId.ToString());
                pb.Junction = "or";
            }
            catch (Exception ex)
            {
                // not a valid long
            }
            pb.Junction = ""; // need this empty space before calling EndGroup
            pb.EndGroup();

            scList = DataRepository.SurveyCustomerProvider.Find(pb.GetParameters());

Saturday, November 1, 2014

Checkbox does not change its checked value after postback

 have a checkbox from where I get the checked value but the first time works great but then I doesn't change at all after postback and always returns true.
I'm just doing this

bool accepted = this.chkAccepted.Checked;
My checkbox is inside a control. Not repeater not directly in a page.
<asp:CheckBox ID="chkAccepted" runat="server" Checked="true"/>Accepted

The first time it starts checked = true. I click my button first postback and work fine, then I uncheck, click my button but the checked is still true.
The first time it starts checked = true. I uncheck the checkbox and I click my button first postback and work fine, then I check, click my button but the checked is true, then I uncheck again and is always checked = true.
So, what is the bug for this?
I have another checkbox in the same control which has no Checked property initialized and always works fine. So how can I solve this problem please?



I realized that it's a .NET bug after some research. So when the property Checked of the checkbox is set to true in the aspx, this causes the problem. So, I removed this property and in the Page_Load event(server side) I initialized the checkboxes as true inside a Page.IsPostBack == false. And that's solved my problem.


solved

<asp:CheckBox ID="chkRem"  value="true" runat="server" Text="تذكرني"  />
  <asp:HiddenField ID="chkremHid" runat="server" />


<script>
   //check box for login
            $('#chkRem').change(function () {
                if ($('#chkRem').prop('checked'))
                    $('#chkremHid').val("True");
                else
                    $('#chkremHid').val("False");
            });

</script>



in code behind
use the hidden field value instead chekbox
c#
string check = chkremHid.Value;



Friday, October 31, 2014

How to get the DataKey value in RowDataBound event for GridView



Please try with following code.
protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string lsDataKeyValue = GridView3.DataKeys[e.Row.RowIndex].Values[0].ToString();
        }
    }

How to Get DataKey value of a Row in RowDataBound or RowCommand Event in ASP.Net GridView control ?


We will normally set the primary key field to the DataKeyNames property of GridView control to identify the row. This little code snippet will help us to find the data keys assocciated with a row in DataBound and RowCommand event in codebehind file.

Refer the below code,
ASPX
  <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
            DataKeyNames="UserID" OnRowDataBound="gvUsers_RowDataBound"
            RowStyle-CssClass="Row" onrowcommand="gvUsers_RowCommand">
                    <Columns>                     
                        <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />    
                         <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />
                         <asp:TemplateField>
                         <ItemTemplate>
                        <asp:Button runat="server" Text="SELECT" CommandName="Select" />                            
                        </ItemTemplate>
                         </asp:TemplateField>                      
                    </Columns>                  
                    <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />
     </asp:GridView>

RowDataBound Event
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {      
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            object objTemp = gvUsers.DataKeys[e.Row.RowIndex].Value as object;
            if (objTemp != null)
            {
                string id = objTemp.ToString(); //Do your operations
            }
         
        }
    }

RowCommand Event
    protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      Control ctl = e.CommandSource as Control;
      GridViewRow CurrentRow = ctl.NamingContainer as GridViewRow;
      object objTemp = gvUsers.DataKeys[CurrentRow.RowIndex].Value as object;
      if (objTemp != null)
      {
          string id = objTemp.ToString(); //Do your operations
      }
    }

call a JQuery function from code behind in C#

I want to call this JQuery function from C# code behind

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "myfunction", "myFunction(params...);", true);

MS in Computer Science with paid training in USA company