Thursday, December 11, 2014

Export Dataset To XML File asp net c#

System.Data.DataSet ds;
//Fill dataset
 
// Get a FileStream object
using (System.IO.StreamWriter xmlDoc = new System.IO.StreamWriter(Server.MapPath("~/writeabledir/xmlDoc.xml"), false))
{
 // Apply the WriteXml method to write an XML document
 ds.WriteXml(xmlDoc);
}

Saturday, December 6, 2014

jQuery ui dialog change title after load-callback

Save dialog in a variable

$dialog = $("#dialog-message").dialog({
   modal: true,
   autoOpen: false,
   buttons: {
   Ok: function () {
   $(this).dialog("close");
   }
   }
});
$('[data-action="show"]').click(function () {
   //Change title
   $dialog.dialog('option''title', $(this).data('product'));
   //Open dialog
   $dialog.dialog('open');
 
   return false;
});

Friday, December 5, 2014

How to combine date from one field with time from another field - MS SQL Server

SELECT CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME) AS CombinedDateTime
 
--OR
--if date part is missing and you want to format time in asp net
SELECT CAST(GETDATE() AS DATE) + CAST(MyTime AS DATETIME) AS CombinedDateTime

MultiView cannot have children of type

Multiview must be followed by the following type
  1. CompleteWizardStep
  2. CreateUserWizardStep
  3. TemplatedWizardStep
  4. ViewWizardStep
And make sure runat="server" is applied on each tag

Thursday, December 4, 2014

Get class from string in asp net c# using Reflection

Assembly assembly = Assembly.Load("AssemblyName.ClassName");
Class class = (Class)assembly.CreateInstance("AssemblyName.ClassName"true);

asp net c# Get executing assembly name

// Full-name, e.g. MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
string exeAssembly = Assembly.GetEntryAssembly().FullName;
 
// or just the "assembly name" part (e.g. "MyApplication")
string exeAssemblyName = Assembly.GetEntryAssembly().GetName().Name;

Saturday, November 22, 2014

Exporting CLR Assemblies from SQL Server back to .dll files

Solution 1

Create a sql server project and import the database. It will import all the assemblies in the assemblies folder

How to set the database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission as TRUE?

EXEC sp_changedbowner 'sa'
ALTER DATABASE [dbase] SET trustworthy ON

asp net c# How do you convert Byte Array to Hexadecimal String, and vice versa?

public byte[] GetStringToBytes(string value)
{
 var shb = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(value);
 return shb.Value;
}
 
public string GetBytesToString(byte[] value)
{
 var shb = new System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary(value);
 return shb.ToString();
}

Friday, November 14, 2014

Remove the last character in a string in T-SQL?

SELECT SUBSTRING( 'string' , 1 , LEN( 'string' ) - 1 )
--or
SELECT LEFT( 'string' , LEN( 'string' ) - 1 )

Thursday, November 13, 2014

Inner image and text of asp:LinkButton disappears after postback

This problem is now known to Microsoft, and they have published an official statement and workaround on the Microsoft Connect issue 718810: LinkButton controls collection lost on postback.
Microsoft statement is:
Thank you for the feedback. This seems like an oddity with the fact that the LinkButton control allows either direct text content via the Text property or in markup, or sub-controls via the Controls collection or markup. The workaround is to use a placeholder as the root content for the control and place the desired mixed content in there, e.g.
<asp:LinkButton runat="server">    <asp:PlaceHolder runat="server">        This is some text.</br>        <asp:Label runat="server">This is a control</asp:Label>    </asp:PlaceHolder>
</asp:LinkButton> 

Tuesday, November 11, 2014

“ClickOnce does not support the request execution level 'requireAdministrator.'”

Turns out that under the Security tab, "Enable ClickOnce security settings" was checked. Even though I didn't check it.

Anyway, unchecking that stopped ClickOnce giving me errors. That took a while to find...

Monday, November 10, 2014

.net How to allow a datetimepicker control to accept null value?

use the DateTimePicker controls Checked Property to determine where user has selected a value or not.
To Show Check inside DateTimePicker  control set the ShowCheckBox property to true
e.g.

DateTime? generatedOn = null;
if (dateTimePicker1.Checked)
    generatedOn = dateTimePicker1.Value;

Sunday, November 9, 2014

Load, save connection string in app.config dynamically

Code

Configuration config;
private void Form1_Load(object sender, EventArgs e)
{
    config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
 
private void btnLoadSettings_Click(object sender, EventArgs e)
{
    System.Data.SqlClient.SqlConnectionStringBuilder cb = new System.Data.SqlClient.SqlConnectionStringBuilder();
    cb.ConnectionString = config.ConnectionStrings.ConnectionStrings["cs"].ConnectionString;
 
    boxServer.Text = cb.DataSource;
    boxUsername.Text = cb.UserID;
    boxPassword.Text = cb.Password;
    boxDatabase.Text = cb.InitialCatalog;
    cboxIntegratedSecurity.Checked = cb.IntegratedSecurity;
}
 
private void cboxIntegratedSecurity_CheckStateChanged(object sender, EventArgs e)
{
    pnlUserPass.Enabled = !cboxIntegratedSecurity.Checked;
}
 
private void btnSaveCS_Click(object sender, EventArgs e)
{
    System.Data.SqlClient.SqlConnectionStringBuilder cb = new System.Data.SqlClient.SqlConnectionStringBuilder();
 
    cb.DataSource = boxServer.Text;
    cb.UserID = boxUsername.Text;
    cb.Password = boxPassword.Text;
    cb.InitialCatalog = boxDatabase.Text;
    cb.IntegratedSecurity = cboxIntegratedSecurity.Checked;
 
    config.ConnectionStrings.ConnectionStrings["cs"].ConnectionString = cb.ConnectionString;
 
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("connectionStrings");
 
    MessageBox.Show("Connection string saved successfully");
}

Design


Friday, November 7, 2014

asp net How to register script at the very bottom of the page

Use the following
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
 
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
 
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
    String cstext1 = "alert('Script at the bottom of form tag');";
    cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}

Friday, October 31, 2014

Remove sql server 2005 express tools to Install SQL Server 2008

Solution
  1. Open Run Menu and type regedit.
  2. It will open Registry Editor
  3. Now go to following location.
(32Bit) HKLM> Software > Microsoft > Microsoft SQL Server > 90

(64Bit) HKLM> Software > Wow6432Node > Microsoft > Microsoft SQL Server > 90

Remove Registry Key 90.

Move focus to next row in table on enter

$('......').keypress(function (e) {
    if (e.which == 13) {
        $(this).closest('tr').next().find('.....').select();
        return false;
    }
});

SSDT – Error SQL70001 This statement is not recognized in this context

Change the build action of the script file to None from Build

The file 'src' is not a valid here because it doesn't expose a type.

The problem may stem from
[assemblyAssemblyCulture(".....")]
in your Properties/AssemblyInfo.cs file

try removing or commenting out the line

Monday, October 20, 2014

How to Set Active Tab in jQuery Ui

<script>
    $( "#tabs" ).tabs({ selected: # });
</script>

How to create a three column table in ASP.Net Repeater

<asp:Repeater runat="server" DataSourceID="testds">
    <HeaderTemplate>
        <table class="items">
    </HeaderTemplate>
    <ItemTemplate>
        <%# (Container.ItemIndex + 3) % 3 == 0 ? "<tr>" : string.Empty%>
        <td>
            <img src='/blablabla/<%# Eval("id"%>.jpg' alt="" /></td>
        <%# (Container.ItemIndex + 3) % 3 == 2 ? "</tr>" : string.Empty%>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

Wednesday, October 1, 2014

How do you kill all current connections to a SQL Server database

-- set your current connection to use master otherwise you might get an error
USE master
GO
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
GO
ALTER DATABASE YourDatabase SET MULTI_USER
GO

Unable to Log In --Cookies Are Blocked Due To Unexpected Output

Just make sure wp-config.php file is in utf-8 encoding; if not save file in utf-8 encoding

To save file in utf-8 encoding use notepad, notepad++ or equivalent editor then do a save as to save file in proper encoding

Wednesday, September 24, 2014

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

<configuration>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
</configuration>

Friday, September 19, 2014

Wednesday, September 17, 2014

Delete all data in SQL Server database

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 
 
EXEC sp_MSForEachTable 'SET QUOTED_IDENTIFIER ON; DELETE FROM ?' 
GO 
 
-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' 
GO
 
-- Reseed identity columns
EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'', RESEED, 0)'

DELETE failed because the following SET options have incorrect settings: QUOTED_IDENTIFIER

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 
 
EXEC sp_MSForEachTable 'SET QUOTED_IDENTIFIER ON; DELETE FROM ?' 
GO 
 
-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' 
GO
 
-- Reseed identity columns
EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'', RESEED, 0)'

Tuesday, September 16, 2014

Console.WriteLine equivalent in ASP.Net

System.Diagnostics.Debug.WriteLine("Message");

Messages are displayed in output window

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

try
{
    //...........
    dc.SaveChanges();
}
catch (DbEntityValidationException ex)
{
    foreach (var eve in ex.EntityValidationErrors)
    {
        System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
}
Look for errors in the output window during debugging

LINQ Lamda Syntax - Selecting multiple columns

use the new keyword
var parent = dc.Forms.Select(f => new { f.FormID, f.ModuleId })

How to check if string contains a string from a string array

Using LINQ Any
string[] rpts = { "rpt""rtp""Rpt""Report" };
using if and any to check whether string contains any item from array
if (rpts.Any(url.Contains))
{
    ........
}

Monday, September 8, 2014

Bind a Dictionary to a DropDownList

Dictionary<stringstring> openWith = new Dictionary<stringstring>();
 
// Add some elements to the dictionary. There are no  
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt""notepad.exe");
openWith.Add("bmp""paint.exe");
openWith.Add("dib""paint.exe");
openWith.Add("rtf""wordpad.exe");
 
DDL.DataSource = openWith
    .Select(r => new KeyValuePair<stringstring>(r.Key, r.Value))
    .ToList();
DDL.DataTextField = "Key";
DDL.DataValueField = "Value";
DDL.DataBind();

call change() event handler if I select radio button programatically

$(function () {
    $('input[name=type]').change(function () {
        alert($(this).val());
    });
    $('input[value=SV]').attr('checked''checked').trigger('change');
});

Saturday, September 6, 2014

EF5: Cannot attach the file ‘{0}' as database '{1}'

Go to View -> SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode!

Delete the database

The model backing the context has changed since the database was created

Database.SetInitializer<YourDbContext>(null);
or


Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDbContext>());
for later versions

Wednesday, August 27, 2014

Computed Columns and CASE SQL Server

CASE
       WHEN shipdate is NULL AND orderdate < DATEADD( dd, -7, GETDATE()) THEN 3
       WHEN shipdate is NOT NULL THEN 2
       ELSE 1
END

Wednesday, August 20, 2014

How to convert type 'byte[]' to 'System.Data.Linq.Binary'

System.Data.Linq.Binary has a constructor taking 1 argument of byte[]:

var byt = new System.Data.Linq.Binary(bytes);

Friday, August 15, 2014

Get datakey value inside listview itemcommand

ListViewItem lvi = e.Item;
int id = Convert.ToInt32(ListView1.DataKeys[lvi.DataItemIndex].Value);

Tuesday, August 12, 2014

How do I use an INSERT statement's OUTPUT clause to get the identity value?

DECLARE @OutputTbl TABLE (ID INT)
 
DECLARE @ID int
 
INSERT INTO TBL(Name, Email)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('ABC', 'email@gmail.com')
 
SELECT @ID = ID FROM @OutputTbl ot

Friday, August 1, 2014

Disable button on form submit using jQuery

JQuery
<script>
    $('form').submit(function () {
        $(this).children('[type=submit]').prop('disabled'true);
    });
</script>

Saturday, June 14, 2014

How to get list of available SQL Servers instances using C#

/// <summary>
/// Get SQL Server Instances if possible
/// </summary>
private static string[] GetSQLServerInstances()
{
    List<string> instances = new List<string>();
    try
    {
        System.Data.Sql.SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
        System.Data.DataTable table = instance.GetDataSources();
 
        foreach (System.Data.DataRow row in table.Rows)
        {
            instances.Add(row[0] + "\\" + row[1]);
        }
    }
    catch (Exception)
    {
 
    }
    return instances.ToArray();
}

Deserialization error in XML document(1,1)

Use StreamReader instead of StringReader

Generate C# class from XML

Using XSD

from visual studio tools menu run "Developer Command Prompt for VS2013" as administrator

switch to the directory where your xml file exists using "cd yourxmlfolder"
then type

d:\yourxmlfolder> xsd yourxmlfile.xml

this will generate a yourxmlfile.xsd

then type

d:\yourxmlfolder> xsd yourxmlfile.xsd /classes

and your done

Tuesday, June 10, 2014

How to get the 4(n) right / left most numbers from an integer SQl SERVER

n right most numbers from an integer
SELECT CAST(RIGHT(CAST(Int AS VARCHAR(20)), [n]) AS BIGINT)
n left most numbers from an integer
SELECT CAST(LEFT(CAST(Int AS VARCHAR(20)), [n]) AS BIGINT)

Tuesday, June 3, 2014

Microsoft HTTPAPI/2.0 use Port 80 – Cannot Start WAMP Apache

Stop the SQL Server Reporting Services

How to check if a byte array is a valid image?

public static bool IsValidImage(byte[] bytes)
{
    try
    {
        using (MemoryStream ms = new MemoryStream(bytes))
            System.Drawing.Image.FromStream(ms);
    }
    catch (ArgumentException)
    {
        return false;
    }
    return true;
}

Convert int to guid in C# and SQL Server

C#
public static Guid Int2Guid(int value)

{
    byte[] bytes = new byte[16];
    BitConverter.GetBytes(value).CopyTo(bytes, 0);
    return new Guid(bytes);
}
SQL Server

CAST(CONVERT(BINARY(16), REVERSE(CONVERT(BINARY(16), 13))) AS uniqueidentifier)

How to change screen orientation in android emulator?

Ctrl+F12  or Num 7 is the keyboard shortcut.

Sunday, May 25, 2014

Wednesday, May 7, 2014

.NET - How can you split a 'caps' delimited string into an array?

System.Text.RegularExpressions.Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))""$1 ");

Smo: How to get the table a foreign key refers to

foreach (ForeignKey key in currentTable.ForeignKeys)
{
    foreach (ForeignKeyColumn column in key.Columns)
    {
        Console.WriteLine("Column: {0} is a foreign key to Table: {1}", column.Name, key.ReferencedTable);
    }
}

Extension methods must be defined in a non-generic static class

change this
public class Stats
    {
        public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
        {
            return k == 0 ? new[] { new T[0] } :
              elements.SelectMany((e, i) =>
                elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
        }
    }
to

public static class Stats
    {
        public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
        {
            return k == 0 ? new[] { new T[0] } :
              elements.SelectMany((e, i) =>
                elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
        }
    }

LINQ Difference Between Select and SelectMany

SelectMany flattens queries that return lists of lists

Algorithm to return all combinations of k elements from n

public static class Stats
    {
        public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
        {
            return k == 0 ? new[] { new T[0] } :
              elements.SelectMany((e, i) =>
                elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
        }
    }

How to calculate the difference between two dates using PHP?

<?php
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

Tuesday, April 22, 2014

LINQ Case statement within Count asp net c#

var statu = from x in dc.Attendance
            group x by 1 into g
            select new
            {
                ID = g.Key,
                Presents = g.Where(t => t.AttendanceStatus == "Present").Count(),
                Absents = g.Where(t => t.AttendanceStatus == "Absent").Count(),
                Leaves = g.Where(t => t.AttendanceStatus == "Leave").Count(),
            };

Monday, April 21, 2014

unique key based on 2 or more columns in SQl Server 2005 or later

CREATE UNIQUE NONCLUSTERED INDEX IX ON Tbl
(
        Col1  ,
        Col2 ,
 Col3
) WITH( IGNORE_DUP_KEY = OFF)

Breaking out of a nested loop c# aspnet

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        if (exit_condition)
        {
            // cause the outer loop to break:
            i = INT_MAX;
            // break the inner loop
            break;
        }
    }
}

IIS - this configuration section cannot be used at this path (configuration locking?)

For Windows 7

  • Click "Start button"
  • in the search box, enter "Turn windows features on or off"
  • in the features window, Click: "Internet Information Services"
  • Click: "World Wide Web Services"
  • Click: "Application Development Features"
  • Check (enable) the features. I checked all but CGI.


For Windows Server 2012

  • Configure Web Server(IIS) inside roles and features
  • Add all features including dot net framework 4

Thursday, April 17, 2014

How to get name of all tables in ms sql database aspnet c#

public System.Collections.Generic.Dictionary<stringstring> GetAllTables(System.Data.SqlClient.SqlConnection _connection)
{
    if (_connection.State == System.Data.ConnectionState.Closed)
        _connection.Open();
    System.Data.DataTable dt = _connection.GetSchema("Tables");
    System.Collections.Generic.Dictionary<stringstring> tables = new System.Collections.Generic.Dictionary<stringstring>();
    foreach (System.Data.DataRow row in dt.Rows)
    {
        if (row[1].ToString().Equals("BASE TABLE"StringComparison.OrdinalIgnoreCase)) //ignore views
        {
            string tableName = row[2].ToString();
            string schema = row[1].ToString();
            tables.Add(tableName, schema);
        }
    }
    _connection.Close();
    return tables;
}

Wednesday, April 16, 2014

Monday, April 14, 2014

asp net c# crystal report server side printing

Exposing printer settings to the SYSTEM account

When a printer is installed on a computer, its settings are stored in the HKEY_CURRENT_USER registry key. IIS runs under the context of the local SYSTEM account. It has access to the HKEY_USERS registry key, but not to the HKEY_CURRENT_USERS subkey, which is only available to a user logged on to the computer.
By default, no printers are defined in the HKEY_USERS key. You can add them by exporting three keys from the HKEY_CURRENT_USERS key and importing them to the HKEY_USERS key
NoteCaution Incorrectly editing the registry might severely damage your system. Make sure you back up valued data before making changes to the registry.
To make printer settings available to the SYSTEM account:
  1. Check that the current user on the Web server has the required printer(s) installed.
  2. To launch the Registry Editor, type regedit in the Start>Run dialog box and click OK.
  3. Select the HKEY_USERS\.DEFAULT\Software\Microsoft\Windows NT\CurrentVersion key and export the registry key from the File or Registry menu.
  4. Specify a name and location in the Export Registry File dialog box and click Save.
  5. This file provides a backup if you need to restore the registry.
  6. In the HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion key, select the Devices subkey and export the registry key.
  7. Specify the name devices.reg and a temporary location in the Export Registry File dialog box and click Save.
  8. Repeat steps 5 and 6 for the PrinterPorts and Windows subkeys, naming the files printerports.reg and windows.reg.
  9. Open devices.reg in Notepad (do not use TextPad or another editor), replace the string HKEY_CURRENT_USER with the string HKEY_USERS\.DEFAULT (note that there is a dot before DEFAULT), and save the file.
  10. Repeat step 8 for printerports.reg and windows.reg.
  11. Double-click each of the edited files to import them into the registry.
  12. Restart IIS so that the configuration changes take effect.

Best way to iterate over a Dictionary in asp net c#?

foreach (KeyValuePair<int, string> entry in dicObj)
{
   //body
}

Sunday, March 9, 2014

asp net FormView DataItemCount always return 0

Precautions
  1. Make sure to call DataItemCount on FormView DataBound Event rather than on Page_Load
  2. Make sure FormView's DefaultMode is set to Edit or Readonly not Insert
 Thanks

Friday, February 14, 2014

EXEC Stored Procedure on a row without cursor

DECLARE @StudentID INT = -1
WHILE (= 1) 
BEGIN
 SELECT TOP 1 @StudentID = StudentId
 FROM Students
 WHERE StudentId > @StudentID
 ORDER BY StudentId
 IF @@ROWCOUNT = 0
  BREAK;
 EXEC dbo.ProcedureName @StudentId
END

Saturday, February 8, 2014

How to see active SQL Server connections for database

Using simple select statements
SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0 AND DB_NAME(dbid) LIkE '{DBNAME}'
GROUP BY 
    dbid, loginame
;
or using stored procedure
sp_who or sp_who

Thursday, January 30, 2014

how to set multiple items are selected in ListBox?

List<string> Authors = new List<string>(new string[] { "Jk Rowling""Morris Mano" });
 
foreach (ListItem item in ListBox1.Items)
{
    if (Authors.Contains(item.Text))
        item.Selected = true;
}

Subquery returning csv written values in a Main Query Column

select 
    categorie, 
    stuff((select ', ' + id
           from table2 t2 where t1.categorie = t2.categorie
           for xml path('')),
          1,2,'') [IDs]
from table1 t1

Wednesday, January 29, 2014

Crystal Reports Viewer won't go past page 2

The problem may stem from setting the Crystal Report Viewer control's ReportSource during the Page_Load event. This causes the paging information to be over-written with each page load, so the "current page" is re-set to 1 when it should be at 2. As an easy solution, you can move the code that sets ReportSource into Page_Init
        protected void Page_Init(object sender, EventArgs e)
        {
            if (IsPostBack && Session["rd"] != null)
            {
                crv.ReportSource = (ReportDocument)Session["rd"];
            }
        }

Monday, January 27, 2014

asp net Register a Control assembly on web.config

How to Register a Control assembly on web.config
<pages theme="Normal" clientIDMode="Static">
    <controls>
        <add assembly="CKEditor.NET" namespace="CKEditor.NET" tagPrefix="CKEditor"/>
    </controls>
</pages>

Thursday, January 23, 2014

How to log the user out using FormsAuthentication.SignOut()

FormsAuthentication.SignOut();
Session.Abandon();
 
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
cookie1.Path = FormsAuthentication.FormsCookiePath;
cookie1.HttpOnly = true;
 
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId""");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
 
FormsAuthentication.RedirectToLoginPage();

How to Disable RequiredFieldValidator with javascript

<script>
    ValidatorEnable(document.getElementById('RequiredFieldValidator1'), false);
</script>

Sunday, January 19, 2014

Remove transparency in images with C#

Remove Transparency from png's in c# or asp net c#
public void RemoveTransparency(string filename)
{
   using (System.Drawing.Bitmap src = new System.Drawing.Bitmap(filename))
   {
      using (System.Drawing.Bitmap target = new System.Drawing.Bitmap(src.Size.Width, src.Size.Height))
      {
          using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(target))
          {
             g.Clear(System.Drawing.Color.White);
             g.DrawImage(src, 0, 0);  
          }
          target.Save("Full path of file");
      }
   }
}

Saving Image To MemoryStream asp net c#

Use this function to convert image to byte array
public byte[] GetByte(System.Drawing.Image image)
{
    using (System.IO.MemoryStream m = new System.IO.MemoryStream())
    {
        image.Save(m, image.RawFormat);
        return m.ToArray();
    }
}

Saturday, January 11, 2014

Errror casting System.DBNulll to System.Byte[]

Consider this line of code
imgSign.ImageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])dr["Signature"]);  
now if dr["Signature"] returns a null value compiler will raise the error
Error casting System.DBNulll to System.Byte[]

to handler this error we can either use try catch or if statement to see if dr["Signature"] is not null

if (dr["Signature"] != DBNull.Value)
imgSign.ImageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])dr["Signature"]);

Sunday, January 5, 2014

Sql temp table with primary key and autoincrement field?

CREATE TABLE #TBL
(
ID INT IDENTITY(1, 1) primary key ,
SOMETHING VARCHAR(50)
);

How to set multiple data attributes using the jQuery.attr()

$('#img').attr({
     alt: 'Beijing Brush Seller',
     title: 'photo by Kelly Clark'
});

Saturday, January 4, 2014

Save jSign image to file using php

Setup jSign first
in head section of page
<!-- you load jquery somewhere above here ... -->
<!--[if lt IE 9]>
<script type="text/javascript" src="libs/flashcanvas.js"></script>
<![endif]-->
in body section
<form action="save-sign.php" method="post">
 Sign here
 <div id="signature"></div>
 <input type="hidden" name="hdnSignature" id="hdnSignature" />
 <input type="button" id="btn_submit" value="Submit Form" />
</form>
<script>
$(function () {
 'use strict';
 var $sigdiv = $("#signature");
 $sigdiv.jSignature();// inits the jSignature widget.
 
 //save data to hidden field before submiting the form
 $('#btn_submit').click(function () {
  var datapair = $sigdiv.jSignature("getData""image");
  $('#hdnSignature').val(datapair[1]);
 //now submit form 
document.forms[0].submit();
  });
 });
</script>
and save-sign.php file should be like this
<?php
$sign = '';
if(isset($_POST['hdnSignature']))
{
 $sign = $_POST['hdnSignature'];
 $path = "path to file.png";
 $sign = base64_decode($sign); //convert base64
 file_put_contents($path$sign); //save to file
 //all done
}
?>