Skip to main content

Posts

Showing posts with the label some code

Value cannot be null when trying to get WebAPI Token using Postman

Well, Server Error in '/' Application. Value cannot be null. Parameter name: value Description:  An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details:  System.ArgumentNullException: Value cannot be null. Parameter name: value Source Error: Line 431: { Line 432: AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); Line 433: var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); Line 434: AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); Line 435: It happened because when i created the user using Configuration Seed (i'm using EF Code First), i'm not filled the Security Stamp that is why the error occured because when the Security Stamp is null, it...

Dropdown List from object List in MVC View

In previous months, i have opportunity to play along with MVC after a while using EF Code First and MVC 5. So today the snippet about creating DropdownList from object List rather than List of SelectListItem let's say u have this Company Class [Key] public int CompanyId { get; set; } public string Name { get; set; } public string Code { get; set; } and u want to display dropdown list based on Code as Text and Id as Value in the View u create a SelectList based on that field @Html.LabelFor(model => model.Brand.Company, htmlAttributes: new { @class = "control-label col-md-2" }) @Html.DropDownList("selectedCompany", Model.Companies.Select(_ => new SelectListItem { Text = _.Code, Value = _.CompanyId.ToString(), Selected = _.CompanyId.ToString() == Model.Brand.Company.CompanyId.ToString() }) ) the Model is a simple ViewModel that have Brands and Brand object sorry for the format, can not make it right :D

sp_msforeachtable - Quick counting table rows

i just starting to play along with SSIS and SSAS and i came up with this trick to show wether my data has been populate into staging or data warehouse table so here is the script EXEC sp_MSForEachTable " DECLARE @count AS INT SET @count=0 SELECT @count = ISNULL(SUM(1), 0) FROM ? PRINT ""?: "" + CONVERT(VARCHAR, @Count) , @whereand = "ORDER BY 1" "  until then

sp_msforeachtable - Delete data in all tables in SQL Server database

hi all, just remember to post this useful tips -- disable all constraints EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" -- delete data in all tables EXEC sp_MSForEachTable "DELETE FROM ?" -- enable all constraints exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" --if some of the tables have identity columns we may want to reseed them EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)" see u then

sp_MsForEachTable - compare data between tables

usually i will using temporary table to build dynamic query to compare the value for two indentical database between two servers but few weeks ago i know undocumented sp_msforeachtable stored procedure and gain some advantage for using it exec sp_MSforeachtable  @command1 = ' IF EXISTS( SELECT top 1 * FROM [server2].db_name.? EXCEPT  SELECT top 1 * FROM ?   ) PRINT ''?'' ' just make sure u use "." in first syntax because sp_msforeachtable return "dbo.table_name" for parameters reference please see this link see u

create ClickOnce shortcut at Startup

currently there are needs to add some shortcut based on ClickOnce Application that being deployed, it's obvious we can't create it manually because of the installation path here is some remedy :D, u need to add reference to System.Deployment, System.IO,  System.Reflection  if (ApplicationDeployment.IsNetworkDeployed) { string publisherName = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)).Company; string productName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); startupPath = Path.Combine(startupPath, productName) + ".appref-ms"; if (!File.Exists(startupPath)) { string allProgramsPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs); string shortcutPath = Path.Combine(allProgramsPath, publisherName); shortcutPath = Path.Combine...

Find all Database size in SQL Server

hi, just came across a very good script from Pinal Dave u can see all database information in one place here the script SELECT database_id, CONVERT(VARCHAR(25), DB.name) AS dbName, CONVERT(VARCHAR(10), DATABASEPROPERTYEX(name, 'status')) AS [Status], state_desc, (SELECT COUNT(1) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'rows') AS DataFiles, (SELECT SUM((size*8)/1024) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'rows') AS [Data MB], (SELECT COUNT(1) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'log') AS LogFiles, (SELECT SUM((size*8)/1024) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'log') AS [Log MB], user_access_desc AS [User access], recovery_model_desc AS [Recovery model], CASE compatibility_level WHEN 60 THEN '60 (SQL Server 6.0)' WHEN 65 THEN '65 (SQL Server 6.5)' WHEN 7...

WCF: The underlying connection was closed

hi, just got an error for couple of days when try to return a model contain child record using Entity Framework and DBContext i have this Role class that contain list of User within that Role so when i try to get specific Role along with the User it give me an error "The underlying connection was closed " after searching alot i came up with this great solution disabled proxy creation and lazy loading or  manually in Entity DBContext constructor it run succesfully and can return UserInRole but if i filled up the table then the error comes, so we need to  Preserving Object Reference in WCF  but i came with this very useful  Andrey Chabster Blog  that using custom attribute that needed for the Service contract and Operation contract  until then

The version of SQL Server in use does not support datatype datetime2

hi again,  just came up with this error in Entity Framework  the reason is because my development using SQL2008 express edition but the preproduction using SQL2005 and the solution is fairly simple  Open your EDMX in a file editor (or “open with…” in Visual Studio and select XML Editor). At the top you will find the storage model and it has an attribute ProviderManifestToken. This has should have the value 2008. Change that to 2005, recompile and everything works after trying up for 2 hours :D until then

Renaming SQL Server Default Instance

hi all, found another intresting stuff to post scenario: u change windows computer name and suddenly the query that contains SQL Server link server or anything that currently connect to ur "changed computer" is not working try using this query in SSMS -– Get the current name of the SQL Server instance for later comparison. SELECT @@servername –- Remove server from the list of known remote and linked servers on the local instance of SQL Server. EXEC master.dbo.sp_dropserver ‘[SERVER NAME]‘ –- Define the name of the local instance of SQL Server. EXEC master.dbo.sp_addserver ‘[NEW SERVER NAME]‘, ‘local’ –- Get the new name of the SQL Server instance for comparison. SELECT @@servername after try, u must restart sql server services...then check if the query is working now see u

Get Child and Parent from hierarchy Table using Common Table Expression (CTE) - SQL 2005 and above

hi, just want to post something that might be useful DECLARE @a AS TABLE ( autoid INT  , name VARCHAR(20) , parentid INT ) INSERT INTO @a (autoid, name, parentid) SELECT 1, '1', 0 UNION ALL SELECT 2, '1.1', 1 UNION ALL SELECT 3, '1.2', 1 UNION ALL SELECT 4, '1.2.1', 3 UNION ALL SELECT 5, '2.1', 2 UNION ALL SELECT 6, '3.1', 3 UNION ALL SELECT 7, '3.2', 3 /* 1 1 0 2 1.1 1 3 1.2 1 4 1.2.1 3 5 2.1 2 6 3.1 3 7 3.2 3 */ /* Get Parent Records from child '1.2.1' return: 1.2 (parent from '1.2.1') 1 (parent from '1.2') */ ;WITH    employeeMaster       AS ( SELECT   p.autoid ,                     p.parentid ,                     p.[name]            FROM     @a p            WHERE ...

Find size of SQL Server tables and other objects with stored procedure

my colleague needs a query to seek for all tables in certain Database then use it to display informati on such as: Created Date, Rows in that tables, etc at first i look over sp_spaceused but it end up wrapping query which is hard because undocumented and it failed :( also considerations can be used for SQL 2000 so i google it and found this link , it works for SQL 2000 and above i tweak a bit to meet my requirement but credit goes to  Richard Ding here is the query that i used USE master; GO IF OBJECT_ID(N'dbo.sp_SOS', N'P') IS NOT NULL   DROP PROCEDURE dbo.sp_SOS; GO CREATE PROCEDURE dbo.sp_SOS   @DbName sysname = NULL,   @SchemaName sysname = NULL,   @ObjectName sysname = N'%',   @TopClause nvarchar(20) = NULL,   @ObjectType nvarchar(50) = NULL,   @ShowInternalTable nvarchar(3) = NULL,   @OrderBy nvarchar(100) = NULL,   @UpdateUsage bit = 0 AS /*=============================================================...

Print Escape Character for printer Barcode in .NET

fiuhh, this case is one of the most annoying 'simple' approach requirement is to send 'barcode' to printer directly, because often we using Image print (creating image on the fly then send it to barcode printer)..this one althought works but often the image become blur / discarded so we need to 'communicate' to barcode printer using its 'language' the 'language' depends on the printer itself..in my case, we using SATO barcode printer so the 'language' is SBPL  (visit the link for more info) first we need to design the label we can use SBPL and design it 'on the fly' make us a little bit crazy or we can use SATO LABEL Gallery Free to do the job and generate SBPL equivalent for us so we can use it in our code after we design it, we use "Print to file" method for the printer then print it so we can see what its send to the printer the generated SBPL will contain 'unseen' character in visual studio ID...

Reset Identity Column Value in SQL Server

if u have identity column and of course before deployed it to production, u'll need to test the value when u done, u probably want to reset it to initial value (0 for example) so u have 'fresh' data for production u'll be need to use this syntax DBCC CHECKIDENT (orders, RESEED, 0) PS: the next value will be always +1, so in my case next value will be 1 until then

Date and Time format in SQL

this are some DATE and TIME format to use in SQL that i found when i'm googling a little YY-MM-DD SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD] SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), '/', '-') AS [YY-MM-DD] 99-01-24 YYYY-MM-DD SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD] SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 111), '/', '-') AS [YYYY-MM-DD] 1999-01-24 MM/YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 3), 5) AS [MM/YY] SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 3), 4, 5) AS [MM/YY] 08/99 MM/YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 103), 7) AS [MM/YYYY] 12/2005 YY/MM SELECT CONVERT(VARCHAR(5), GETDATE(), 11) AS [YY/MM] 99/08 YYYY/MM SELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM] 2005/12 Month DD, YYYY  1 SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY] July 04, 2006 1 Mon YYYY 1 SELECT SUBSTRING(CONV...

Search specific string inside Stored Procedure, View, Function, Trigger, Table Name, Table Field in SQL Server

this query can be used to search specific string inside, no need to right click  - modify - and search manually from Query designer / SSMS DECLARE @NextString NVARCHAR(40) DECLARE @Pos INT DECLARE @NextPos INT DECLARE @String NVARCHAR(40) DECLARE @Delimiter NVARCHAR(40) DECLARE @Query nvarchar(2000) DECLARE @WHERE nvarchar(1000) DECLARE @Query2 nvarchar(2000) DECLARE @Where2 nvarchar(1000) SET @Query =  'SELECT DISTINCT so.name, ' +    'CASE so.xtype ' +     'WHEN ''P'' THEN ''SPROC'' ' +     'WHEN ''IF'' THEN ''FUNCTION'' ' +     'WHEN ''FN'' THEN ''FUNCTION'' ' +     'WHEN ''V'' THEN ''VIEW'' ' +     'WHEN ''U'' THEN ''TABLE'' ' +     'WHEN ''TR'' THEN ''TRIGGER'' ' +    'END AS [TYPE] ' +  'FROM...

Cannot obtain the schema rowset "DBSCHEMA_TABLES_INFO" for OLE DB provider "SQLNCLI" for linked server [linked_server_name]

just got this error when try to execute query against LinkServer (SQL 2000) from SQL 2005 eventhough the link can create but i can't do 4 parts query select * from LINKED.DB.DBO.TABLE the problem because SQL 2000 needs to run certain SP that not exists in master so the LINK query can run create   procedure  sp_tables_info_rowset_64       @table_name  sysname ,       @table_schema      sysname   =   null,           @table_type  nvarchar ( 255 )   =   null as declare @Result int set @Result = 0 exec  @Result =  sp_tables_info_rowset  @table_name , @table_schema ,  @table_type this  solution  originally POST  by  Marek Adamczuk until then

Entity Framework 4 and SQL Server 2000

it can be done!!.. (Microsoft .NET,Microsoft SQL Server,Database) by Jason Skowronek on 11/07/2011 If you are unfortunate enough to have to support applications running on legacy SQL Server 2000 databases like me, you are probably aware of the limitation of Visual Studio 2010 and Entity Framework 4.0 for SQL Server 2000 . There are plenty of articles out there on work-arounds. I find this one the most direct and feasible. Granted, I have not looked into possible version issue that may result in doing it this way, but for the various applications on which I have worked, it is sufficiently elegant and functional. This a work-around. Let me repeat, this is a work-around! . Here are the steps to add a new Entity Framework 4 entity context to a Visual Studio 2010 project: Download the base entity data model for SQL Server 2000 file and save it to the project folder to which you wish to add the SQL 2000 entity context. Do NOT add it to your pr...